package com.cgc.venus.server.app.service;

import com.cgc.venus.server.app.bean.*;
import com.cgc.venus.server.app.inter.AppManageService;
import com.cgc.venus.server.core.base.AbstractBaseService;
import com.cgc.venus.server.core.bean.response.VenusResponseStatus;
import com.cgc.venus.server.core.exception.VenusException;
import com.cgc.venus.server.core.harbor.HarborService;
import com.cgc.venus.server.core.harbor.model.Repository;
import com.cgc.venus.server.core.harbor.model.Tag;
import com.cgc.venus.server.core.k8s.inter.K8sManageService;
import com.cgc.venus.server.core.k8s.inter.K8sStorageService;
import com.cgc.venus.server.core.utils.DateUtil;
import com.cgc.venus.server.core.utils.StringUtil;
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.api.model.apps.*;
import io.fabric8.kubernetes.api.model.apps.DaemonSet;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder;
import io.fabric8.kubernetes.api.model.apps.DeploymentStatus;
import io.fabric8.kubernetes.api.model.apps.DeploymentStrategy;
import io.fabric8.kubernetes.api.model.apps.ReplicaSet;
import io.fabric8.kubernetes.api.model.autoscaling.v1.HorizontalPodAutoscaler;
import io.fabric8.kubernetes.api.model.autoscaling.v1.HorizontalPodAutoscalerStatus;
import io.fabric8.kubernetes.api.model.batch.Job;
import io.fabric8.kubernetes.api.model.extensions.*;
import io.fabric8.kubernetes.api.model.networking.NetworkPolicy;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by 业哥 on 2017/11/15.
 * 应用管理
 */
@org.springframework.stereotype.Service
public class AppManageServiceImpl extends AbstractBaseService implements AppManageService {

    @Autowired
    private K8sManageService k8sManageService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private HarborService harborService;

    @Autowired
    private AppManageConfigBean appManageConfigBean;

    @Autowired
    private K8sStorageService k8sStorageService;


    /*
    * 根据上传的yaml文件,创建应用
    * */
    @Override
    public String createAppByYaml(AppManageBean appManageBean, String yamlContent) throws VenusException {
        String message = "";

        // 是否为空
        if (StringUtils.isBlank(yamlContent)) return "Yaml content is empty";

        // 获得king: xxxxx
        String kind = AppManageConfigBean.getValueFromYaml(yamlContent, "kind", "\n");

        if (StringUtils.isBlank(kind)) return "Yaml kind not find";

        String appName = AppManageConfigBean.getValueFromYaml(yamlContent, "name:", "\n").replaceAll("name:", "").trim();

        /*
        * 创建以下常用的资源管理对象后, 数据存到mysql
        *
            1. Pod
            2. deployment
            3. statefulset
            4. replicaSet
            5. Job
            6. ReplicationController
            7. DaemonSet

        * */

        try {
            if (kind.equals(AppManageConfigBean.Kind_Namespace)) {
                Namespace namespace = k8sManageService.createNamespaceByYaml(yamlContent);
                // 从返回对象仲取得 空间,镜像,等信息
                message = namespace == null ? "Namespace: " + appName + " Yaml 语法有误" : "";
            } else if (kind.equals(AppManageConfigBean.Kind_Node)) {
                Node node = k8sManageService.createNodeByYaml(yamlContent);
                message = node == null ? "Node: " + appName + "  Yaml 语法有误" : "";
            } else if (kind.equals(AppManageConfigBean.Kind_Pod)) {
                Pod pod = k8sManageService.createPodByYaml(yamlContent);

                // yaml 文件语法错误
                if (pod == null) return "Pod: " + appName + "  Yaml 语法有误";

                // 记录数据到数据库
                // 1:重新赋值
                appManageBean.setNamespace(pod.getMetadata().getNamespace().trim());
                appManageBean.setAppNameKube(pod.getMetadata().getName().trim());
                appManageBean.setAppKind(pod.getKind().trim());

                // 获取容器数组
                List<Container> containerList = pod.getSpec().getContainers();
                String[] image = getImageFromContainer(containerList).split(";");

                appManageBean.setImageName(image[0]);
                appManageBean.setImageVersion(image[1]);

                // 2: update
                createAppByYaml(appManageBean);

            } else if (kind.equals(AppManageConfigBean.Kind_Service)) {
                Service service = k8sManageService.createServiceByYaml(yamlContent);
                message = service == null ? "Service: " + appName + "  Yaml 语法有误" : "";
            } else if (kind.equals(AppManageConfigBean.Kind_PersistentVolume)) {
                PersistentVolume persistentVolume = k8sManageService.createPersistentVolumeByYaml(yamlContent);
                //statusCode = persistentVolume == null ? 0 : 1;
                message = persistentVolume == null ? "PersistentVolume: " + appName + "  Yaml 语法有误" : "";
            } else if (kind.equals(AppManageConfigBean.Kind_PersistentVolumeClaim)) {
                PersistentVolumeClaim persistentVolumeClaim = k8sManageService.createPersistentVolumeClaimByYaml(yamlContent);
                //statusCode = persistentVolumeClaim == null ? 0 : 1;
                message = persistentVolumeClaim == null ? "PersistentVolumeClaim: " + appName + "  Yaml 语法有误" : "";
            } else if (kind.equals(AppManageConfigBean.Kind_Deployment)) {
                Deployment deployment = k8sManageService.createDeploymentByYaml(yamlContent);

                if (deployment == null) return "Deployment: " + appName + "  Yaml 语法有误";

                // 记录数据到数据库
                // 1:重新赋值
                appManageBean.setNamespace(deployment.getMetadata().getNamespace().trim());
                appManageBean.setAppNameKube(deployment.getMetadata().getName().trim());
                appManageBean.setAppKind(deployment.getKind().trim());

                // 获取容器数组
                List<Container> containerList = deployment.getSpec().getTemplate().getSpec().getContainers();
                String[] image = getImageFromContainer(containerList).split(";");

                appManageBean.setImageName(image[0]);
                appManageBean.setImageVersion(image[1]);

                // 2: update
                createAppByYaml(appManageBean);

            } else if (kind.equals(AppManageConfigBean.Kind_Secret)) {
                Secret secret = k8sManageService.createSecretByYaml(yamlContent);
                //statusCode = secret == null ? 0 : 1;
                message = secret == null ? "Secret: " + appName + "  Yaml 语法有误" : "";
            } else if (kind.equals(AppManageConfigBean.Kind_StatefulSet)) {
                StatefulSet statefulSet = k8sManageService.createStatefulSetByYaml(yamlContent);
                // 3:记录数据到数据库
                if (statefulSet == null) return "StatefulSet: " + appName + "  Yaml 语法有误";

                // 记录数据到数据库
                // 1:重新赋值
                appManageBean.setNamespace(statefulSet.getMetadata().getNamespace().trim());
                appManageBean.setAppNameKube(statefulSet.getMetadata().getName().trim());
                appManageBean.setAppKind(statefulSet.getKind().trim());

                // 获取容器数组
                List<Container> containerList = statefulSet.getSpec().getTemplate().getSpec().getContainers();
                String[] image = getImageFromContainer(containerList).split(";");

                appManageBean.setImageName(image[0]);
                appManageBean.setImageVersion(image[1]);

                // 2: update
                createAppByYaml(appManageBean);
            } else if (kind.equals(AppManageConfigBean.Kind_ServiceAccount)) {
                ServiceAccount serviceAccount = k8sManageService.createServiceAccountByYaml(yamlContent);
                //statusCode = serviceAccount == null ? 0 : 1;
                message = serviceAccount == null ? "ServiceAccount: " + appName + "  Yaml 语法有误" : "";
            } else if (kind.equals(AppManageConfigBean.Kind_ReplicaSet)) {
                ReplicaSet replicaSet = k8sManageService.createReplicaSetByYaml(yamlContent);
                // 4:记录数据到数据库
                if (replicaSet == null) return "ReplicaSet: " + appName + "  Yaml 语法有误";

                // 记录数据到数据库
                // 1:重新赋值
                appManageBean.setNamespace(replicaSet.getMetadata().getNamespace().trim());
                appManageBean.setAppNameKube(replicaSet.getMetadata().getName().trim());
                appManageBean.setAppKind(replicaSet.getKind().trim());

                // 获取容器数组
                List<Container> containerList = replicaSet.getSpec().getTemplate().getSpec().getContainers();
                String[] image = getImageFromContainer(containerList).split(";");

                appManageBean.setImageName(image[0]);
                appManageBean.setImageVersion(image[1]);

                // 2: update
                createAppByYaml(appManageBean);
            } else if (kind.equals(AppManageConfigBean.Kind_ReplicationController)) {
                ReplicationController replicationController = k8sManageService.createReplicationControllerByYaml(yamlContent);
                // 5:记录数据到数据库
                //statusCode = replicationController == null ? 0 : 1;
                if (replicationController == null) return "ReplicationController: " + appName + "  Yaml 语法有误";

                // 记录数据到数据库
                // 1:重新赋值
                appManageBean.setNamespace(replicationController.getMetadata().getNamespace().trim());
                appManageBean.setAppNameKube(replicationController.getMetadata().getName().trim());
                appManageBean.setAppKind(replicationController.getKind().trim());

                // 获取容器数组
                List<Container> containerList = replicationController.getSpec().getTemplate().getSpec().getContainers();
                String[] image = getImageFromContainer(containerList).split(";");

                appManageBean.setImageName(image[0]);
                appManageBean.setImageVersion(image[1]);

                // 2: update
                createAppByYaml(appManageBean);
            } else if (kind.equals(AppManageConfigBean.Kind_Job)) {
                Job job = k8sManageService.createJobByYaml(yamlContent);
                // 6:记录数据到数据库
                if (job == null) return "Job: " + appName + "  Yaml 语法有误";

                // 记录数据到数据库
                // 1:重新赋值
                appManageBean.setNamespace(job.getMetadata().getNamespace().trim());
                appManageBean.setAppNameKube(job.getMetadata().getName().trim());
                appManageBean.setAppKind(job.getKind().trim());

                // 获取容器数组
                List<Container> containerList = job.getSpec().getTemplate().getSpec().getContainers();
                String[] image = getImageFromContainer(containerList).split(";");

                appManageBean.setImageName(image[0]);
                appManageBean.setImageVersion(image[1]);

                // 2: update
                createAppByYaml(appManageBean);
            } else if (kind.equals(AppManageConfigBean.Kind_Ingress)) {
                Ingress ingress = k8sManageService.createIngressByYaml(yamlContent);
                message = ingress == null ? "Ingress: " + appName + "  Yaml 语法有误" : "";
            } else if (kind.equals(AppManageConfigBean.Kind_ConfigMap)) {
                ConfigMap configMap = k8sManageService.createConfigMapByYaml(yamlContent);
                message = configMap == null ? "ConfigMap: " + appName + "  Yaml 语法有误" : "";
            } else if (kind.equals(AppManageConfigBean.Kind_HorizontalPodAutoscaler)) {
                HorizontalPodAutoscaler horizontalPodAutoscaler = k8sManageService.createHorizontalPodAutoscalerByYaml(yamlContent);
                message = horizontalPodAutoscaler == null ? "HorizontalPodAutoscaler: " + appName + "  Yaml 语法有误" : "";
            } else if (kind.equals(AppManageConfigBean.Kind_NetworkPolicy)) {
                NetworkPolicy networkPolicy = k8sManageService.createNetworkPolicyByYaml(yamlContent);
                message = networkPolicy == null ? "NetworkPolicy: " + appName + "  Yaml 语法有误" : "";
            } else if (kind.equals(AppManageConfigBean.Kind_DaemonSet)) {
                DaemonSet daemonSet = k8sManageService.createDaemonSetByYaml(yamlContent);
                // 7:记录数据到数据库
                //statusCode = daemonSet == null ? 0 : 1;

                if (daemonSet == null) return "DaemonSet: " + appName + "  Yaml 语法有误";

                // 记录数据到数据库
                // 1:重新赋值
                appManageBean.setNamespace(daemonSet.getMetadata().getNamespace().trim());
                appManageBean.setAppNameKube(daemonSet.getMetadata().getName().trim());
                appManageBean.setAppKind(daemonSet.getKind().trim());

                // 获取容器数组
                List<Container> containerList = daemonSet.getSpec().getTemplate().getSpec().getContainers();
                String[] image = getImageFromContainer(containerList).split(";");

                appManageBean.setImageName(image[0]);
                appManageBean.setImageVersion(image[1]);

                // 2: update
                createAppByYaml(appManageBean);
            }
        } catch (Exception e) {
            String errorMsg = e.getMessage();
            if (StringUtils.isNotBlank(errorMsg)) {
                int message_index = errorMsg.indexOf("Message:");
                int status_index = errorMsg.indexOf("Received status:");
                if (message_index != -1 && status_index != -1) {
                    errorMsg = errorMsg.substring(message_index + 9, status_index);
                }
                message = kind + "; " + appName + ": " + errorMsg;
            } else {
                message = kind + "; " + appName + ": Yaml文件语法错误,请检查";
            }

        }
        return message;
    }

    private String getImageFromContainer(List<Container> containerList) {
        StringBuilder imageSB = new StringBuilder();
        StringBuilder imageVersionSB = new StringBuilder();
        int containerSize = containerList.size();

        for (int i = 0; i < containerSize; i++) {
            Container container = containerList.get(i);
            String image = container.getImage();
            // 不要ip:端口
            image = image.substring(image.indexOf("/") + 1);
            imageSB.append(image.substring(0, image.indexOf(":")).trim());
            imageVersionSB.append(image.split(":")[1].trim());
            if (i < containerSize - 1) {
                imageSB.append("\n");
                imageVersionSB.append("\n");
            }
        }
        return imageSB.toString() + ";" + imageVersionSB.toString();
    }


    /*
    * 2: 根据上传的yaml,创建应用,并保存一条记录到数据里面
    * @param AppManageBean 应用实体类
    * */
    @Override
    public int createAppByYaml(AppManageBean appManageBean) throws VenusException {
        String namespace = appManageBean.getNamespace();
        String appNameKube = appManageBean.getAppNameKube();
        String appKind = appManageBean.getAppKind();

        String sql = "";
        List<Object> objectList = new ArrayList<Object>();
        int row = 0;

        if (existApp(namespace, appNameKube, appKind)) {
            // 修改
            sql = "UPDATE t_app_manage SET " +
                    "app_name=?, " +
                    "image_name=?, " +
                    "image_version=?, " +
                    "described=?," +
                    "deploy_type=?, " +
                    "last_update_time=NOW() " +
                    "WHERE " +
                    "app_name_kube = ? AND " +
                    "namespace = ? AND " +
                    "app_kind = ? ";
            objectList.add(appManageBean.getAppName());
            objectList.add(appManageBean.getImageName());
            objectList.add(appManageBean.getImageVersion());
            objectList.add(appManageBean.getDescribed());
            objectList.add(appManageBean.getDeployType());
            objectList.add(appManageBean.getAppNameKube());
            objectList.add(appManageBean.getNamespace());
            objectList.add(appManageBean.getAppKind());

            row = jdbcTemplate.update(sql, objectList.toArray());
        } else {
            sql = "INSERT INTO t_app_manage(" +
                    "id," +
                    "app_name," +
                    "app_name_kube," +
                    "app_kind," +
                    "image_name," +
                    "image_version," +
                    "described," +
                    "namespace," +
                    "deploy_type," +
                    "create_time," +
                    "last_update_time) " +
                    "VALUES(?,?,?,?,?,?,?,?,?,NOW(),NOW())";
            // 新增
            objectList.add(StringUtil.getUUID());
            objectList.add(appManageBean.getAppName());
            objectList.add(appManageBean.getAppNameKube());
            objectList.add(appManageBean.getAppKind());
            objectList.add(appManageBean.getImageName());
            objectList.add(appManageBean.getImageVersion());
            objectList.add(appManageBean.getDescribed());
            objectList.add(appManageBean.getNamespace());
            objectList.add(appManageBean.getDeployType());

            row = jdbcTemplate.update(sql, objectList.toArray());
        }
        return row;
    }

    /*
   * 根据空间名字,应用名称(k8s里面的),应用资源类型,判断是否存在重复数据
   * @param namespace
   * @param appNameKube
   * @param appKind 应用资源类型
   * */
    @Override
    public boolean existApp(String namespace, String appNameKube, String appKind) throws VenusException {
        String sql = "SELECT id FROM t_app_manage  WHERE app_name_kube = ? AND namespace = ? AND app_kind = ? ";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(appNameKube);
        objectList.add(namespace);
        objectList.add(appKind);

        Map<String, Object> map = null;
        try {
            map = jdbcTemplate.queryForMap(sql, objectList.toArray());
        } catch (EmptyResultDataAccessException ex) {
            return false;
        }
        if (map.size() == 0 || map == null) return false;
        return true;
    }

    /*
    * 查询应用
    * @param page
      * @param pageSize
    * @param queryKey
    * @param queryStatus
     * @param namespace
  * */
    @Override
    public List<AppManageBean> queryApps(int page, int pageSize, String queryKey, String queryStatus, String namespace) throws VenusException {
        // 分页查询
        String sql = "";
        page = (page - 1) * pageSize;
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(namespace);

        if ("all".equals(queryStatus) && StringUtils.isBlank(queryKey)) {
            sql = "SELECT  " +
                    "id, app_name AS appName, app_name_kube AS appNameKube, app_kind AS appKind, image_name AS imageName, image_version AS " +
                    "imageVersion, described, namespace,create_time  AS createTime, last_update_time AS lastUpdateTime FROM  t_app_manage WHERE namespace = ? ORDER BY create_time DESC  LIMIT ?,?";
            objectList.add(page);
            objectList.add(pageSize);
        }

        if ("all".equals(queryStatus) && StringUtils.isNotBlank(queryKey)) {
            sql = "SELECT id, app_name AS appName, app_name_kube AS appNameKube, app_kind AS appKind, image_name AS imageName, image_version AS " +
                    "imageVersion, described, namespace,create_time  AS createTime, last_update_time AS lastUpdateTime FROM  t_app_manage WHERE namespace = ? AND " +
                    "app_name LIKE ? OR app_name_kube LIKE ? ORDER BY create_time DESC  LIMIT ?,?";
            objectList.add("%" + queryKey + "%");
            objectList.add("%" + queryKey + "%");
            objectList.add(page);
            objectList.add(pageSize);
        }


        if (!"all".equals(queryStatus) && StringUtils.isNotBlank(queryKey)) {
            sql = "SELECT id, app_name AS appName, app_name_kube AS appNameKube, app_kind AS appKind, image_name AS imageName, image_version AS " +
                    "imageVersion, described, namespace,create_time  AS createTime, last_update_time AS lastUpdateTime FROM  t_app_manage WHERE namespace = ? AND " +
                    "app_name LIKE ? OR app_name_kube LIKE ? ORDER BY create_time DESC  ";
            objectList.add("%" + queryKey + "%");
            objectList.add("%" + queryKey + "%");

        }

        if (!"all".equals(queryStatus) && StringUtils.isBlank(queryKey)) {
            sql = "SELECT id, app_name AS appName, app_name_kube AS appNameKube, app_kind AS appKind, image_name AS imageName, image_version AS " +
                    "imageVersion, described, namespace,create_time  AS createTime, last_update_time AS lastUpdateTime FROM  t_app_manage WHERE namespace = ? " +
                    " ORDER BY create_time DESC  ";
        }


        List<AppManageBean> maps = new ArrayList<AppManageBean>();
        try {
            maps = jdbcTemplate.query(sql, new RowMapper<AppManageBean>() {
                public AppManageBean mapRow(ResultSet rs, int rowNum) throws SQLException {
                    /*AppManageBean appManageBean = new AppManageBean();
                    appManageBean.setId(rs.getString("id"));
                    appManageBean.setAppName(rs.getString("appName"));
                    appManageBean.setAppNameKube(rs.getString("appNameKube"));
                    appManageBean.setAppKind(rs.getString("appKind"));
                    appManageBean.setImageName(rs.getString("imageName"));
                    appManageBean.setImageVersion(rs.getString("imageVersion"));
                    appManageBean.setDescribed(rs.getString("described"));
                    appManageBean.setNamespace(rs.getString("namespace"));
                    Timestamp fromDateStamp = rs.getTimestamp("createTime");
                    // 时间差
                    String fromDate = DateUtil.TimeStamp2Date(fromDateStamp,DateUtil.yyyy_MM_dd_HH_mm_ss);
                    String toDate = DateUtil.getCurrentTime(DateUtil.yyyy_MM_dd_HH_mm_ss);
                    String timeDiff = DateUtil.getTimeDifference(DateUtil.yyyy_MM_dd_HH_mm_ss,fromDate,toDate);
                    appManageBean.setCreateTime(fromDate);
                    appManageBean.setTimeDiff(timeDiff);
                    Timestamp lastUpdateTime = rs.getTimestamp("lastUpdateTime");
                    appManageBean.setLastUpdateTime(DateUtil.TimeStamp2Date(lastUpdateTime,DateUtil.yyyy_MM_dd_HH_mm_ss));*/
                    return getAppBean(rs);
                }
            }, objectList.toArray());
        } catch (EmptyResultDataAccessException ex) {
            return maps;
        }
        return maps;
    }


    @Override
    public long countApps(String queryKey, String namespace) throws VenusException {
        String sql = "SELECT  " +
                "id FROM  t_app_manage WHERE namespace = ? ";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(namespace);
        if (StringUtils.isNotBlank(queryKey)) {
            sql = "SELECT id  FROM  t_app_manage WHERE namespace = ? AND " +
                    "app_name LIKE '%" + queryKey + "%' OR app_name_kube LIKE '%" + queryKey + "%' ";
        }

        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
        try {
            maps = jdbcTemplate.queryForList(sql, objectList.toArray());
        } catch (EmptyResultDataAccessException ex) {
            return 0;
        }
        return maps.size();

    }

    @Override
    public String getDeploymentReplicas(String namespace, String appNameKube) throws VenusException {
        Deployment deployment = k8sManageService.getDeployment(namespace, appNameKube);
        DeploymentStatus deploymentStatus = deployment.getStatus();
        // 总的副本数
        int totalR = 0;
        try {
            totalR = deployment.getSpec().getReplicas().intValue();
        } catch (NullPointerException nn) {
            totalR = 0;
        }
        // 可用的副本数
        int readyR = 0;
        try {
            readyR = deploymentStatus.getReadyReplicas();
        } catch (NullPointerException n) {
            readyR = 0;
        }
        return readyR + "/" + totalR;
    }

    @Override
    public String getStatefulSetReplicas(String namespace, String appNameKube) throws VenusException {
        StatefulSet statefulSet = k8sManageService.getStatefulSet(namespace, appNameKube);
        StatefulSetStatus statefulSetStatus = statefulSet.getStatus();
        // 总的副本数
        int totalR = 0;
        try {
            totalR = statefulSet.getSpec().getReplicas().intValue();
        } catch (NullPointerException nn) {
            totalR = 0;
        }
        // 可用的副本数
        int readyR = 0;
        try {
            readyR = statefulSetStatus.getReadyReplicas().intValue();
        } catch (NullPointerException n) {
            readyR = 0;
        }
        return readyR + "/" + totalR;
    }

    /*
    * 根据应用ID,获取应用信息
    * */
    @Override
    public AppManageBean getAppManageBeanById(String appId) throws VenusException {
        String sql = "SELECT " +
                "id, " +
                "app_name AS appName, " +
                "app_name_kube AS appNameKube, " +
                "app_kind AS appKind, " +
                "image_name AS imageName, " +
                "image_version AS imageVersion, " +
                "described, " +
                "namespace," +
                "create_time  AS createTime, " +
                "last_update_time AS lastUpdateTime " +
                "FROM  t_app_manage WHERE id = ? ";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(appId);
        AppManageBean appManageBean = new AppManageBean();
        try {
            appManageBean = this.jdbcTemplate.queryForObject(sql, new RowMapper<AppManageBean>() {
                public AppManageBean mapRow(ResultSet rs, int rowNum) throws SQLException {
                    AppManageBean app = new AppManageBean();
                    app.setId(rs.getString("id"));
                    app.setAppName(rs.getString("appName"));
                    app.setAppNameKube(rs.getString("appNameKube"));
                    app.setAppKind(rs.getString("appKind"));
                    app.setImageName(rs.getString("imageName"));
                    app.setImageVersion(rs.getString("imageVersion"));
                    app.setDescribed(rs.getString("described"));
                    app.setNamespace(rs.getString("namespace"));
                    Timestamp createTime_stamp = rs.getTimestamp("createTime");
                    Timestamp lastUpdateTime_stamp = rs.getTimestamp("lastUpdateTime");
                    app.setCreateTime(DateUtil.TimeStamp2Date(createTime_stamp, DateUtil.yyyy_MM_dd_HH_mm_ss));
                    app.setLastUpdateTime(DateUtil.TimeStamp2Date(lastUpdateTime_stamp, DateUtil.yyyy_MM_dd_HH_mm_ss));
                    return app;
                }
            }, objectList.toArray());
        } catch (EmptyResultDataAccessException e) {
            return appManageBean;
        }

        return appManageBean;
    }

    /*
    * 根据应用类型,获得应用实例数
    * */
    @Override
    public String getReplicasByKind(String appKind, String namespace, String appNameKube) throws VenusException {
        String replicas = "";
        if (AppManageConfigBean.Kind_Deployment.indexOf(appKind) != -1) {
            replicas = getDeploymentReplicas(namespace, appNameKube);
        } else if (AppManageConfigBean.Kind_StatefulSet.indexOf(appKind) != -1) {
            replicas = getStatefulSetReplicas(namespace, appNameKube);
        } else if (AppManageConfigBean.Kind_DaemonSet.indexOf(appKind) != -1) {

        }
        return replicas;
    }



    @Override
    public String getAppStatus(String replicas, String createTime) throws VenusException {

        String[] replicasArr = replicas.split("/");
        int readyR = Integer.valueOf(replicasArr[0]);
        int totalR = Integer.valueOf(replicasArr[1]);

        String status = AppManageConfigBean.APP_STATUS_RUNNING;

        if (createTime.indexOf("秒") != -1 && readyR != totalR) {
            status = AppManageConfigBean.APP_STATUS_CREATEING;
        } else if (totalR > readyR) {
            status = AppManageConfigBean.APP_STATUS_ERROR;
        } else if (readyR == 0 && totalR == 0) {
            status = AppManageConfigBean.APP_STATUS_CLOSE;
        }
        return status;
    }

    /*
    * 得到pod 状态
    * @param namespace 空间名称
    * @param appNameKube 应用名
    * */
    @Override
    public List<AppManageBean> getPodStatus(String namespace, String appNameKube) throws VenusException {
        PodList podList = k8sManageService.getPodList(namespace);
        List<Pod> pods = podList.getItems();
        List<AppManageBean> appManageBeanList = new ArrayList<AppManageBean>();
        int podsSize = pods.size();
        //  遍历
        for (int i = 0; i < podsSize; i++) {
            Pod pod = pods.get(i);
            if (pod == null) continue;

            // pod name
            String podName = pod.getMetadata().getName();

            // 过滤
            //if (podName.indexOf(appNameKube) == -1) continue;

            // 重启数
            int restartCount = 0;
            // 获取创建时间
            String createTime = pod.getMetadata().getCreationTimestamp().replaceAll("T", " ").replaceAll("Z", "");
            createTime = DateUtil.calculate(DateUtil.yyyy_MM_dd_HH_mm_ss, createTime, 28800000 - 240000);

            // 状态
            String podStatus = "";
            String podStatusMessage = "";

            PodStatus status = pod.getStatus();

            // 1: 先获得pod的生命周期-- phase
            String phase = status.getPhase();

            podStatus = phase;

            // 2: pod 生命周期需要满足的条件
            //List<PodCondition> podConditionList = status.getConditions();

            // 3: 所有容器运行状态
            List<ContainerStatus> containerStatusList = status.getContainerStatuses();

            boolean isAdd = true;

            // 4: 判断
            // 遍历pod 里面的容器,查看具体是哪一个容器出现问题
            for (ContainerStatus containerStatus : containerStatusList) {
                // 获得容器所属名称
                String containerName = containerStatus.getName();

                // 过滤
                if (!containerName.equals(appNameKube)) {
                    isAdd = false;
                    break;
                }

                // 是否准备状态
                boolean ready = containerStatus.getReady();
                restartCount = restartCount + containerStatus.getRestartCount();
                if (!ready && !"Running".equals(podStatus)) {
                    // 获取容器
                    ContainerState containerState = containerStatus.getState();
                    ContainerStateWaiting containerStateWaiting = containerState.getWaiting();
                    ContainerStateTerminated containerStateTerminated = containerState.getTerminated();
                    String reason = "";
                    String message = "";
                    if (containerStateWaiting != null) {
                        reason = containerStateWaiting.getReason();
                        message = containerStateWaiting.getMessage();

                    }

                    if (containerStateTerminated != null) {
                        reason = containerStateTerminated.getReason();
                        message = containerStateTerminated.getMessage();
                    }
                    podStatusMessage = StringUtils.isBlank(message) ? AppManageConfigBean.APP_POD_STATUS_ERROR : message;
                    podStatus = reason;
                } else if (!ready && "Running".equals(podStatus)) {
                    podStatusMessage = AppManageConfigBean.APP_POD_STATUS_CREATEING;
                    podStatus = AppManageConfigBean.APP_STATUS_CONTAINER_CREATEING;
                }
            }

            if (isAdd) {
                // 设置
                AppManageBean appManageBean = new AppManageBean();
                appManageBean.setAppNameKube(podName);
                appManageBean.setStatus(podStatus);
                appManageBean.setStatusMessage(podStatusMessage);
                appManageBean.setNamespace(namespace);
                appManageBean.setRestartCount(restartCount);
                String timeDiff = DateUtil.getTimeDifference(DateUtil.yyyy_MM_dd_HH_mm_ss, createTime, DateUtil.getCurrentTime(DateUtil.yyyy_MM_dd_HH_mm_ss));
                appManageBean.setTimeDiff(timeDiff);
                appManageBeanList.add(appManageBean);
            }

        }
        return appManageBeanList;
    }

    @Override
    public int updateAppLastTime(String appId) throws VenusException {
        String sql = " UPDATE t_app_manage t SET " +
                "t.last_update_time = NOW() WHERE " +
                "t.id = ? ";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(appId);
        int re = jdbcTemplate.update(sql, objectList.toArray());
        return re;
    }

    /*
   * 灰度升级,更新数据应用的镜像版本号
   * */
    @Override
    public int updateAppImageVersion(String imageVersion, String appId) throws VenusException {
        String sql = " UPDATE t_app_manage t SET t.image_version = ?, t.last_update_time = NOW() WHERE t.id = ?";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(imageVersion);
        objectList.add(appId);
        int re = jdbcTemplate.update(sql, objectList.toArray());
        return re;
    }

    @Override
    public boolean autoScale(String namespace, String hpaName) throws VenusException {
        HorizontalPodAutoscaler horizontalPodAutoscaler = k8sManageService.getHorizontalPodAutoscaler(namespace, hpaName);
        if (horizontalPodAutoscaler != null) {
            return true;
        }
        return false;
    }

    @Override
    public int horizontalScalingDeployment(String namespace, String appNameKube, int replicas) throws VenusException {
        int re = k8sManageService.horizontalScalingDeployment(namespace, appNameKube, replicas);
        return re;
    }

    @Override
    public int horizontalScalingStatefulSet(String namespace, String appNameKube, int replicas) throws VenusException {
        return k8sManageService.horizontalScalingStatefulSet(namespace, appNameKube, replicas);
    }

    /*
    * 重新部署实例
    * */
    @Override
    public int reDeployApp(String appKind, String namespace, String appNameKube, int targetReplicas) throws VenusException {

        int currentReplicas = 0;
        if (AppManageConfigBean.Kind_Deployment.indexOf(appKind) != -1) {
            currentReplicas = k8sManageService.horizontalScalingDeployment(namespace, appNameKube, 0);
            if (currentReplicas == 0) {
                currentReplicas = k8sManageService.horizontalScalingDeployment(namespace, appNameKube, targetReplicas);
            }
        } else if (AppManageConfigBean.Kind_StatefulSet.indexOf(appKind) != -1) {
            currentReplicas = k8sManageService.horizontalScalingStatefulSet(namespace, appNameKube, 0);
            if (currentReplicas == 0) {
                currentReplicas = k8sManageService.horizontalScalingStatefulSet(namespace, appNameKube, targetReplicas);
            }
        }
        return currentReplicas;
    }

    @Override
    public boolean updateDeployment(String namespace, String appNameKube, String targetImage) throws VenusException {
        boolean update = k8sManageService.updateDeployment(namespace, appNameKube, targetImage);
        return update;
    }

    @Override
    public boolean updateStatefunSet(String namespace, String appNameKube, String targetImage) throws VenusException {
        boolean update = k8sManageService.updateStatefunSet(namespace, appNameKube, targetImage);
        return update;
    }

    @Override
    public boolean updateDaemonSet(String namespace, String appNameKube, String targetImage) throws VenusException {
        boolean update = k8sManageService.updateDaemonSet(namespace, appNameKube, targetImage);
        return update;
    }

    @Override
    public List<Tag> getRepositorieTags(String imageName) throws VenusException {
        return harborService.getRepositorieTags(appManageConfigBean.getHarborUrl(), imageName);
    }

    /*
    * 获取自动应用自动伸缩设置的参数
    * */
    @Override
    public AppManageHpaBean getAppHpa(String namespace, String appNameKube) throws VenusException {
        AppManageHpaBean map = new AppManageHpaBean();
        HorizontalPodAutoscaler hpa = k8sManageService.getHorizontalPodAutoscaler(namespace, AppManageConfigBean.getHpaName(appNameKube));
        if (hpa != null) {
            int minR = hpa.getSpec().getMinReplicas().intValue();
            int maxR = hpa.getSpec().getMaxReplicas().intValue();
            int targetCpuPercent = hpa.getSpec().getTargetCPUUtilizationPercentage().intValue();
            map.setMinReplicas(minR);
            map.setMaxReplicas(maxR);
            map.setTargetCpuPercent(targetCpuPercent);
            map.setNamespace(namespace);
            map.setAppNameKube(appNameKube);
        }
        return map;
    }

    /*
   * 应用,新增自动伸缩功能
   * */
    @Override
    public boolean addAutoScaleToApp(AppManageHpaBean appManageHpaBean) throws VenusException {
        String namespace = appManageHpaBean.getNamespace();
        String appNameKube = appManageHpaBean.getAppNameKube();
        String hpaName = AppManageConfigBean.getHpaName(appNameKube);
        int minReplicas = appManageHpaBean.getMinReplicas();
        int maxReplicas = appManageHpaBean.getMaxReplicas();
        int targetCpuPercent = appManageHpaBean.getTargetCpuPercent();
        return k8sManageService.addHorizontalPodAutoscaler(namespace, appNameKube, hpaName, minReplicas, maxReplicas, targetCpuPercent);
    }

    /*
    * 修改,应用自动伸缩参数
    * */
    @Override
    public boolean editAutoScaleToApp(AppManageHpaBean appManageHpaBean) throws VenusException {
        String namespace = appManageHpaBean.getNamespace();
        String hpaName = AppManageConfigBean.getHpaName(appManageHpaBean.getAppNameKube());
        int minReplicas = appManageHpaBean.getMinReplicas();
        int maxReplicas = appManageHpaBean.getMaxReplicas();
        int targetCpuPercent = appManageHpaBean.getTargetCpuPercent();
        return k8sManageService.editHorizontalPodAutoscaler(namespace, hpaName, minReplicas, maxReplicas, targetCpuPercent);
    }

    /*
    * 删除,应用自动伸缩功能
    * */
    @Override
    public boolean deleteAutoScaleToApp(String namespace, String appNameKube) throws VenusException {
        String hpaName = AppManageConfigBean.getHpaName(appNameKube);
        return k8sManageService.deleteHorizontalPodAutoscaler(namespace, hpaName);
    }

    /*
    * 删除应用
    * */
    @Override
    public boolean deleteAppInK8s(String appKind, String namespace, String appNameKube) throws VenusException {
        boolean flag = false;
        if (AppManageConfigBean.Kind_Deployment.indexOf(appKind) != -1) {
            flag = k8sManageService.deleteDeployment(namespace, appNameKube);
        } else if (AppManageConfigBean.Kind_StatefulSet.indexOf(appKind) != -1) {
            flag = k8sManageService.deleteStatefulSet(namespace, appNameKube);
        } else if (AppManageConfigBean.Kind_DaemonSet.indexOf(appKind) != -1) {
            flag = k8sManageService.deleteDaemonSet(namespace, appNameKube);
        } else if (AppManageConfigBean.Kind_Pod.indexOf(appKind) != -1) {
            flag = k8sManageService.deletePod(namespace, appNameKube);
        }
        return flag;
    }

    /*
    * 删除pod
    * */
    @Override
    public boolean deletePod(String namespace, String podName) throws VenusException {
        return k8sManageService.deletePod(namespace, podName);
    }

    @Override
    public int deleteApp(String appId) throws VenusException {
        String sql = "DELETE FROM t_app_manage WHERE id=?";
        List<Object> list = new ArrayList<Object>();
        list.add(appId);
        int row = jdbcTemplate.update(sql, list.toArray());
        return row;
    }

    /*
    * 修改应用描述
    * */
    @Override
    public int editAppDescribed(String appId, String described) throws VenusException {
        String sql = " UPDATE t_app_manage t SET " +
                "t.last_update_time = NOW(), t.described = ? WHERE " +
                "t.id = ? ";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(described);
        objectList.add(appId);
        int re = jdbcTemplate.update(sql, objectList.toArray());
        return re;
    }

    /*
    * 获取pod 事件
    * */
    @Override
    public List<AppManageEventBean> getPodEvents(String namespace, String podName) throws VenusException {
        List<Event> eventList = k8sManageService.getPodEvents(namespace);
        // 筛选
        if (eventList.size() > 0) {
            eventList = eventList.stream().filter(event -> event.getMetadata().getName().indexOf(podName) != -1).collect(Collectors.toList());
        }
        List<AppManageEventBean> appManageEventBeans = new ArrayList<AppManageEventBean>();
        if (eventList.size() > 0) {
            eventList.forEach(event -> {
                AppManageEventBean eventBean = new AppManageEventBean();
                eventBean.setCount(event.getCount().intValue());
                eventBean.setName(event.getMetadata().getName());
                eventBean.setMessage(event.getMessage());
                String firstTime = event.getFirstTimestamp().replaceAll("T", " ").replaceAll("Z", "");
                String lastTime = event.getLastTimestamp().replaceAll("T", " ").replaceAll("Z", "");
                firstTime = DateUtil.calculate(DateUtil.yyyy_MM_dd_HH_mm_ss, firstTime, 28800000);
                lastTime = DateUtil.calculate(DateUtil.yyyy_MM_dd_HH_mm_ss, lastTime, 28800000);
                eventBean.setFirstTimestamp(firstTime);
                eventBean.setLastTimestamp(lastTime);
                appManageEventBeans.add(eventBean);
            });
        }
        return appManageEventBeans;
    }

    /*
    * 根据空间名称,应用名,得到pod 名称呼列表
    * */
    @Override
    public List<String> getPodNames(String namespace, String appNameKube) throws VenusException {
        PodList podList = k8sManageService.getPodList(namespace);
        List<String> podNameList = new ArrayList<String>();
        if (podList != null) {
            List<Pod> pods = podList.getItems();
            if (pods.size() > 0) {
                pods.forEach(pod -> {
                    // pod name
                    String podName = pod.getMetadata().getName();
                    List<ContainerStatus> containerStatusList = pod.getStatus().getContainerStatuses();
                    if (containerStatusList.size() > 0) {
                        String containerName = containerStatusList.get(0).getName();
                        if (containerName.equals(appNameKube)) {
                            podNameList.add(podName);
                        }
                    }
                });
            }
        }
        return podNameList;
    }

    /*
    * 根据标签获取pod list
    * */
    @Override
    public List<AppManageBean> getPodListWithLabel(String namespace, String appNameKube) throws VenusException {
        List<AppManageBean> appManageBeanList = new ArrayList<AppManageBean>();
        PodList podList = k8sManageService.getPodListWithLabels(namespace, "app", appNameKube);
        if (podList == null) return appManageBeanList;
        List<Pod> pods = podList.getItems();

        int podsSize = pods.size();
        if (podsSize > 0) {
            pods.forEach(pod -> {
                // pod name
                String podName = pod.getMetadata().getName();

                // 重启数
                int restartCount = 0;
                // 获取创建时间
                String createTime = pod.getMetadata().getCreationTimestamp().replaceAll("T", " ").replaceAll("Z", "");
                createTime = DateUtil.calculate(DateUtil.yyyy_MM_dd_HH_mm_ss, createTime, 28800000 - 240000);

                // 状态
                String podStatus = "";
                String podStatusMessage = "";

                PodStatus status = pod.getStatus();

                // 1: 先获得pod的生命周期-- phase
                String phase = status.getPhase();

                podStatus = phase;

                // 3: 所有容器运行状态
                List<ContainerStatus> containerStatusList = status.getContainerStatuses();

                // 4: 判断
                // 遍历pod 里面的容器,查看具体是哪一个容器出现问题
                for (ContainerStatus containerStatus : containerStatusList) {
                    // 是否准备状态
                    boolean ready = containerStatus.getReady();
                    restartCount = restartCount + containerStatus.getRestartCount();
                    if (!ready) {
                        // 获取容器
                        ContainerState containerState = containerStatus.getState();
                        ContainerStateWaiting containerStateWaiting = containerState.getWaiting();
                        ContainerStateTerminated containerStateTerminated = containerState.getTerminated();
                        String reason = "";
                        String message = "";
                        if (containerStateWaiting != null) {
                            reason = containerStateWaiting.getReason();
                            message = containerStateWaiting.getMessage();

                        }
                        if (containerStateTerminated != null) {
                            reason = containerStateTerminated.getReason();
                            message = containerStateTerminated.getMessage();
                        }
                        podStatusMessage = StringUtils.isBlank(message) ? AppManageConfigBean.APP_POD_STATUS_ERROR : message;
                        podStatus = reason;
                    }
                }

                // 设置
                AppManageBean appManageBean = new AppManageBean();
                appManageBean.setAppNameKube(podName);
                appManageBean.setStatus(podStatus);
                appManageBean.setStatusMessage(podStatusMessage);
                appManageBean.setNamespace(namespace);
                appManageBean.setRestartCount(restartCount);
                String timeDiff = DateUtil.getTimeDifference(DateUtil.yyyy_MM_dd_HH_mm_ss, createTime, DateUtil.getCurrentTime(DateUtil.yyyy_MM_dd_HH_mm_ss));
                appManageBean.setTimeDiff(timeDiff);
                appManageBeanList.add(appManageBean);
            });
        }

        return appManageBeanList;
    }

    /*
    * 获取所有应用
    * */
    @Override
    public List<AppManageBean> getAllApp() throws VenusException {
        String sql = "SELECT  " +
                "id, app_name AS appName," +
                " app_name_kube AS appNameKube, " +
                "app_kind AS appKind, " +
                "image_name AS imageName, " +
                "image_version AS " +
                "imageVersion, " +
                "described, " +
                "namespace," +
                "create_time  AS createTime, " +
                "last_update_time AS lastUpdateTime " +
                "FROM  t_app_manage ORDER BY create_time DESC";
        List<AppManageBean> maps = new ArrayList<AppManageBean>();
        try {
            maps = jdbcTemplate.query(sql, new RowMapper<AppManageBean>() {
                public AppManageBean mapRow(ResultSet rs, int rowNum) throws SQLException {
                    /*AppManageBean appManageBean = new AppManageBean();
                    appManageBean.setId(rs.getString("id"));
                    appManageBean.setAppName(rs.getString("appName"));
                    appManageBean.setAppNameKube(rs.getString("appNameKube"));
                    appManageBean.setAppKind(rs.getString("appKind"));
                    appManageBean.setImageName(rs.getString("imageName"));
                    appManageBean.setImageVersion(rs.getString("imageVersion"));
                    appManageBean.setDescribed(rs.getString("described"));
                    appManageBean.setNamespace(rs.getString("namespace"));
                    Timestamp fromDateStamp = rs.getTimestamp("createTime");
                    // 时间差
                    String fromDate = DateUtil.TimeStamp2Date(fromDateStamp,DateUtil.yyyy_MM_dd_HH_mm_ss);
                    String toDate = DateUtil.getCurrentTime(DateUtil.yyyy_MM_dd_HH_mm_ss);
                    String timeDiff = DateUtil.getTimeDifference(DateUtil.yyyy_MM_dd_HH_mm_ss,fromDate,toDate);
                    appManageBean.setCreateTime(fromDate);
                    appManageBean.setTimeDiff(timeDiff);
                    Timestamp lastUpdateTime = rs.getTimestamp("lastUpdateTime");
                    appManageBean.setLastUpdateTime(DateUtil.TimeStamp2Date(lastUpdateTime,DateUtil.yyyy_MM_dd_HH_mm_ss));*/

                    return getAppBean(rs);
                }
            });
        } catch (EmptyResultDataAccessException ex) {
            return maps;
        }
        return maps;
    }

    private AppManageBean getAppBean(ResultSet rs) throws SQLException {
        AppManageBean appManageBean = new AppManageBean();
        appManageBean.setId(rs.getString("id"));
        appManageBean.setAppName(rs.getString("appName"));
        appManageBean.setAppNameKube(rs.getString("appNameKube"));
        appManageBean.setAppKind(rs.getString("appKind"));
        appManageBean.setImageName(rs.getString("imageName"));
        appManageBean.setImageVersion(rs.getString("imageVersion"));
        appManageBean.setDescribed(rs.getString("described"));
        appManageBean.setNamespace(rs.getString("namespace"));
        Timestamp fromDateStamp = rs.getTimestamp("createTime");
        // 时间差
        String fromDate = DateUtil.TimeStamp2Date(fromDateStamp, DateUtil.yyyy_MM_dd_HH_mm_ss);
        String toDate = DateUtil.getCurrentTime(DateUtil.yyyy_MM_dd_HH_mm_ss);
        String timeDiff = DateUtil.getTimeDifference(DateUtil.yyyy_MM_dd_HH_mm_ss, fromDate, toDate);
        appManageBean.setCreateTime(fromDate);
        appManageBean.setTimeDiff(timeDiff);
        Timestamp lastUpdateTime = rs.getTimestamp("lastUpdateTime");
        appManageBean.setLastUpdateTime(DateUtil.TimeStamp2Date(lastUpdateTime, DateUtil.yyyy_MM_dd_HH_mm_ss));
        return appManageBean;
    }

    @Override
    public int validateAppName(String appName) throws VenusException {
        String sql = "SELECT id FROM t_app_manage WHERE app_name = ? ";
        List<Object> objectList = new ArrayList<>();
        objectList.add(appName);
        Map<String, Object> map = new HashMap<>();
        try {
            map = jdbcTemplate.queryForMap(sql, objectList.toArray());
        } catch (EmptyResultDataAccessException e) {
            return 0;
        }
        if (map.size() > 0) {
            return 1;
        }

        return 0;
    }

    /*
    * 通过镜像仓库部署应用时候,根据空间名称获取镜像列表,选择部署的镜像
    * */
    @Override
    public List<Repository> getProjectImages(String projectName) throws VenusException {
        List<Repository> repositoryList = new ArrayList<Repository>();
        try {
            repositoryList = harborService.getRepositories(projectName, null, 1, 100000);
        } catch (Exception e) {
            return repositoryList;
        }
        return repositoryList;
    }

    /*
   * 获得镜像数据库的公开镜像
   * */
    @Override
    public List<Repository> getPublicImages() throws VenusException {
        String sql = "SELECT name,create_time FROM t_repository_public ORDER BY last_update_time DESC";
        List<Repository> repositoryList = jdbcTemplate.query(sql, new RowMapper<Repository>() {
            @Override
            public Repository mapRow(ResultSet rs, int i) throws SQLException {
                Repository repository = new Repository();
                repository.setRepositoryName(rs.getString(1));
                Timestamp fromDateStamp = rs.getTimestamp("create_time");
                String createTime = DateUtil.TimeStamp2Date(fromDateStamp, DateUtil.yyyy_MM_dd_HH_mm_ss);
                repository.setCreationTime(createTime);
                return repository;
            }
        });

        return repositoryList;
    }

    /*
    * 获得商店的镜像
    * */
    @Override
    public List<Repository> getSoreImages() throws VenusException {
        String sql = "SELECT name,create_time FROM t_repository_app_store ORDER BY last_update_time DESC";
        List<Repository> repositoryList = jdbcTemplate.query(sql, new RowMapper<Repository>() {
            @Override
            public Repository mapRow(ResultSet rs, int i) throws SQLException {
                Repository repository = new Repository();
                repository.setRepositoryName(rs.getString(1));
                Timestamp fromDateStamp = rs.getTimestamp("create_time");
                String createTime = DateUtil.TimeStamp2Date(fromDateStamp, DateUtil.yyyy_MM_dd_HH_mm_ss);
                repository.setCreationTime(createTime);
                return repository;
            }
        });

        return repositoryList;
    }

    /*
   * 获取镜像基本信息,根据镜像名称
   * */
    @Override
    public ImageBaseBean getImageBase(String imageName) throws VenusException {
        String sql = " SELECT id, " +
                "image, " +
                "described, " +
                " app_kind AS appKind, " +
                "requests_memory AS requestsMemory, " +
                "limits_memory AS limitsMemory," +
                "limits_cpu AS limitsCPU," +
                " replicas," +
                "start_command AS startCommand, " +
                "command," +
                "image_pull_policy AS imagePullPolicy " +
                "FROM t_image_base " +
                "WHERE image = ? ";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(imageName);
        ImageBaseBean imageBaseBean = null;
        try {
            imageBaseBean = jdbcTemplate.queryForObject(sql, new RowMapper<ImageBaseBean>() {
                @Override
                public ImageBaseBean mapRow(ResultSet rs, int i) throws SQLException {
                    ImageBaseBean baseBean = new ImageBaseBean();
                    baseBean.setId(rs.getString("id"));
                    baseBean.setImage(rs.getString("image"));
                    baseBean.setDescribed(rs.getString("described"));
                    baseBean.setAppKind(rs.getString("appKind"));
                    baseBean.setRequestsMemory(rs.getString("requestsMemory"));
                    baseBean.setLimitsMemory(rs.getString("limitsMemory"));
                    baseBean.setReplicas(rs.getInt("replicas"));
                    baseBean.setStartCommand(rs.getInt("startCommand"));
                    baseBean.setCommand(rs.getString("command"));
                    baseBean.setImagePullPolicy(rs.getString("imagePullPolicy"));
                    baseBean.setLimitsCPU(rs.getString("limitsCPU"));
                    return baseBean;
                }
            }, objectList.toArray());
        } catch (EmptyResultDataAccessException e) {
            return imageBaseBean;
        }
        return imageBaseBean;
    }

    /*
    * 获取镜像端口列表,根据镜像名称
    * */
    @Override
    public List<Map<String, Object>> getImagePortList(String imageName) throws VenusException {
        String sql = " SELECT id, " +
                "image," +
                "port," +
                "protocol," +
                "visible," +
                "port_type AS portType, " +
                "node_port AS nodePort," +
                "domain_name AS domainName," +
                "domain_name_type AS domainNameType " +
                "FROM t_image_port " +
                "WHERE image = ? ";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(imageName);
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        try {
            mapList = jdbcTemplate.queryForList(sql, objectList.toArray());
        } catch (EmptyResultDataAccessException e) {
            return mapList;
        }

        if (mapList.size() > 0) {
            mapList.forEach(stringObjectMap -> {
                int visible = (Integer) stringObjectMap.get("visible");
                if (visible > 0) {
                    stringObjectMap.put("visible", true);
                } else {
                    stringObjectMap.put("visible", false);
                }
            });
        }

        return mapList;
    }

    /*
    * 获取镜像的环境变量列表,根据镜像名称
    * */
    @Override
    public List<Map<String, Object>> getImageEnvList(String imageName) throws VenusException {
        String sql = "SELECT id," +
                "image," +
                "env_key AS envKey, " +
                "env_value AS envValue " +
                "FROM t_image_env " +
                "WHERE image = ?";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(imageName);
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        try {
            mapList = jdbcTemplate.queryForList(sql, objectList.toArray());
        } catch (EmptyResultDataAccessException e) {
            return mapList;
        }
        return mapList;
    }

    /*
    * 获取镜像配置卷,根据镜像名称
    * */
    @Override
    public List<Map<String, Object>> getImageConfigVolumes(String imageName) throws VenusException {
        String sql = "SELECT id, " +
                "image, " +
                "mouth_path AS mouthPath, " +
                "config_group AS configGroup, " +
                "config_files AS configFiles " +
                "  FROM t_image_config_volumes " +
                "WHERE image = ?";
        List<Object> objectList = new ArrayList<>();
        objectList.add(imageName);
        List<Map<String, Object>> mapList = new ArrayList<>();
        try {
            mapList = jdbcTemplate.queryForList(sql, objectList.toArray());
        } catch (EmptyResultDataAccessException e) {
            return mapList;
        }
        if (mapList.size() > 0) {
            mapList.forEach(stringObjectMap -> {
                String arr = (String) stringObjectMap.get("configFiles");
                if (StringUtils.isBlank(arr)) {
                    String[] a = new String[0];
                    stringObjectMap.put("configFiles", a);
                    stringObjectMap.put("configFilesArr", a);
                } else {
                    stringObjectMap.put("configFiles", arr.split(","));
                    stringObjectMap.put("configFilesArr", arr.split(","));
                }

            });
        }
        return mapList;
    }

    /*
    * 获取镜像高可用信息
    * */
    @Override
    public ImageHighAvailabilityBean getImageHABean(String imageName) throws VenusException {
        String sql = " SELECT id, " +
                "image," +
                "type," +
                "port," +
                "initial_delay_seconds AS initialDelaySeconds, " +
                "period_seconds AS periodSeconds," +
                " timeout_seconds AS timeoutSeconds," +
                "path" +
                " FROM t_image_high_availability " +
                "WHERE image = ?";
        List<Object> objectList = new ArrayList<>();
        objectList.add(imageName);
        ImageHighAvailabilityBean highAvailabilityBean = null;
        try {
            highAvailabilityBean = jdbcTemplate.queryForObject(sql, new RowMapper<ImageHighAvailabilityBean>() {
                @Override
                public ImageHighAvailabilityBean mapRow(ResultSet rs, int i) throws SQLException {
                    ImageHighAvailabilityBean bean = new ImageHighAvailabilityBean();
                    bean.setId(rs.getString("id"));
                    bean.setImage(rs.getString("image"));
                    bean.setType(rs.getInt("type"));
                    bean.setPort(rs.getInt("port"));
                    bean.setInitialDelaySeconds(rs.getInt("initialDelaySeconds"));
                    bean.setPeriodSeconds(rs.getInt("periodSeconds"));
                    bean.setTimeoutSeconds(rs.getInt("timeoutSeconds"));
                    bean.setPath(rs.getString("path"));
                    return bean;
                }
            }, objectList.toArray());
        } catch (EmptyResultDataAccessException e) {
            return highAvailabilityBean;
        }
        return highAvailabilityBean;
    }

    /*
    * 得到镜像启动参数
    * */
    @Override
    public List<Map<String, Object>> getImageArgsList(String imageName) throws VenusException {
        String sql = " SELECT id,image,arg FROM t_image_command_agrs WHERE image = ? ORDER BY serial_number  ";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(imageName);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            list = jdbcTemplate.queryForList(sql, objectList.toArray());
        } catch (EmptyResultDataAccessException e) {
            return list;
        }
        return list;
    }

    /*
    * 新增镜像基本信息
    * */
    @Override
    public int addImageBase(ImageBaseBean imageBaseBean) throws VenusException {
        String sql = " INSERT INTO t_image_base(" +
                "id," +
                "image," +
                "described," +
                "app_kind," +
                "requests_memory" +
                ",limits_memory," +
                "limits_cpu," +
                "replicas," +
                "start_command," +
                "command," +
                "image_pull_policy," +
                "create_time," +
                "last_update_time) " +
                "VALUES(?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(StringUtil.getUUID());
        objectList.add(imageBaseBean.getImage());
        objectList.add(imageBaseBean.getDescribed());
        objectList.add(imageBaseBean.getAppKind());
        objectList.add(imageBaseBean.getRequestsMemory());
        objectList.add(imageBaseBean.getLimitsMemory());
        objectList.add(imageBaseBean.getLimitsCPU());
        objectList.add(imageBaseBean.getReplicas());
        objectList.add(imageBaseBean.getStartCommand());
        String command = imageBaseBean.getStartCommand() == 1 ? "" : imageBaseBean.getCommand();
        objectList.add(command);
        objectList.add(imageBaseBean.getImagePullPolicy());
        int flag = jdbcTemplate.update(sql, objectList.toArray());
        return flag;
    }

    /*
    * 修改镜像基本信息
    * */
    @Override
    public int editImageBse(ImageBaseBean imageBaseBean) throws VenusException {
        String sql = " UPDATE t_image_base SET " +
                "described=?," +
                "app_kind=?," +
                "requests_memory=?," +
                " limits_memory=?," +
                "limits_cpu=?," +
                "replicas=?," +
                "start_command=?," +
                "command = ?," +
                "image_pull_policy=?," +
                "last_update_time=NOW() " +
                "WHERE " +
                "id = ? ";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(imageBaseBean.getDescribed());
        objectList.add(imageBaseBean.getAppKind());
        objectList.add(imageBaseBean.getRequestsMemory());
        objectList.add(imageBaseBean.getLimitsMemory());
        objectList.add(imageBaseBean.getLimitsCPU());
        objectList.add(imageBaseBean.getReplicas());
        objectList.add(imageBaseBean.getStartCommand());
        String command = imageBaseBean.getStartCommand() == 1 ? "" : imageBaseBean.getCommand();
        objectList.add(command);
        objectList.add(imageBaseBean.getImagePullPolicy());
        objectList.add(imageBaseBean.getId());
        int row = jdbcTemplate.update(sql, objectList.toArray());
        return row;
    }

    /*
    * 新增镜像-端口-信息
    * */
    @Override
    public int batchAddImagePort(List<ImagePortBean> imagePortBeanList, String imageName) throws VenusException {
        String sql = " INSERT INTO t_image_port(" +
                "id," +
                "image," +
                "port," +
                "protocol," +
                "port_type," +
                "node_port," +
                "visible," +
                "domain_name," +
                "domain_name_type," +
                "create_time," +
                "last_update_time) " +
                " VALUES(?,?,?,?,?,?,?,?,?,NOW(),NOW()) ";

        int[] ii = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(java.sql.PreparedStatement ps, int i) throws SQLException {
                ImagePortBean imagePortBean = imagePortBeanList.get(i);
                ps.setString(1, StringUtil.getUUID());
                ps.setString(2, imageName);
                ps.setInt(3, imagePortBean.getPort());
                ps.setString(4, imagePortBean.getProtocol());
                ps.setString(5, imagePortBean.getPortType());
                ps.setInt(6, 8080);
                boolean visible = imagePortBean.isVisible();
                if (visible) {
                    ps.setInt(7, 1);
                } else {
                    ps.setInt(7, 0);
                }
                ps.setString(8, imagePortBean.getDomainName());
                ps.setString(9, imagePortBean.getDomainNameType());
            }

            @Override
            public int getBatchSize() {
                return imagePortBeanList.size();
                //这个方法设定更新记录数，通常List里面存放的都是我们要更新的，所以返回
            }
        });
        return ii.length;
    }

    /*
    * 修改镜像-端口-信息
    * */
    @Override
    public int batchEditImagePort(List<ImagePortBean> imagePortBeanList) throws VenusException {
        String sql = " UPDATE t_image_port SET " +
                "protocol=?, " +
                "port_type=?," +
                "node_port=?," +
                "visible=?," +
                "domain_name=?," +
                "domain_name_type=?," +
                "last_update_time=NOW() " +
                " WHERE " +
                "id = ? " +
                "AND image = ? " +
                "AND PORT = ?";

        int[] ii = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(java.sql.PreparedStatement ps, int i) throws SQLException {
                ImagePortBean imagePortBean = imagePortBeanList.get(i);
                ps.setString(1, imagePortBean.getProtocol());
                ps.setString(2, imagePortBean.getPortType());
                ps.setInt(3, 8080);
                if (imagePortBean.isVisible()) {
                    ps.setInt(4, 1);
                } else {
                    ps.setInt(4, 0);
                }
                ps.setString(5, imagePortBean.getDomainName());
                ps.setString(6, imagePortBean.getDomainNameType());
                ps.setString(7, imagePortBean.getId());
                ps.setString(8, imagePortBean.getImage());
                ps.setInt(9, imagePortBean.getPort());
            }

            @Override
            public int getBatchSize() {
                return imagePortBeanList.size();
            }
        });

        return ii.length;
    }

    /*
    * 获取镜像-端口-信息
    * */
    @Override
    public ImagePortBean getImagePortBean(String imageName, int port) {
        String sql = "  SELECT " +
                "id," +
                "image," +
                "port," +
                "protocol," +
                "port_type AS portType," +
                "node_port AS nodePort," +
                " visible,domain_name AS  domainName, domain_name_type AS  domainNameType  " +
                "FROM t_image_port " +
                "WHERE image = ? AND PORT = ?";
        List<Object> objectList = new ArrayList<>();
        objectList.add(imageName);
        objectList.add(port);
        ImagePortBean imagePortBean = null;
        try {
            imagePortBean = jdbcTemplate.queryForObject(sql, new RowMapper<ImagePortBean>() {
                @Override
                public ImagePortBean mapRow(ResultSet rs, int i) throws SQLException {
                    ImagePortBean imagePortBean1 = new ImagePortBean();
                    imagePortBean1.setId(rs.getString("id"));
                    imagePortBean1.setImage(rs.getString("image"));
                    imagePortBean1.setPort(rs.getInt("port"));
                    imagePortBean1.setProtocol(rs.getString("protocol"));
                    imagePortBean1.setPortType(rs.getString("portType"));
                    imagePortBean1.setNodePort(rs.getInt("nodePort"));
                    int visible = rs.getInt("visible");
                    if (visible > 0) {
                        imagePortBean1.setVisible(true);
                    } else {
                        imagePortBean1.setVisible(false);
                    }
                    imagePortBean1.setDomainName(rs.getString("domainName"));
                    imagePortBean1.setDomainNameType(rs.getString("domainNameType"));
                    return imagePortBean1;
                }
            }, objectList.toArray());
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
        return imagePortBean;
    }

    /*
    * 删除镜像-端口-信息
    * */
    @Override
    public int deleteImagePort(String id) throws VenusException {
        String sql = "DELETE FROM t_image_port WHERE id = ?";
        List<Object> objectList = new ArrayList<>();
        objectList.add(id);
        int row = jdbcTemplate.update(sql, objectList.toArray());
        return row;
    }

    /*
    * 统一处理, 镜像端口信息: 新增,修改
    * */
    @Override
    public int handleImagePort(List<ImagePortBean> imagePortBeanList, String imageName) throws VenusException {
        int size = imagePortBeanList.size();
        List<ImagePortBean> addPortList = new ArrayList<>();
        List<ImagePortBean> editPortList = new ArrayList<>();
        int count = 0;
        if (size > 0) {
            imagePortBeanList.forEach(imagePortBean -> {
                String id = imagePortBean.getId();
                int port = imagePortBean.getPort();
                // 先判断是否存在
                ImagePortBean rePortBean = getImagePortBean(imageName, port);
                if (rePortBean != null) {
                    // 存在
                    editPortList.add(imagePortBean);
                } else {
                    // 不存在
                    addPortList.add(imagePortBean);
                }
            });

            if (addPortList.size() > 0) {
                // 批量新增
                count = count + batchAddImagePort(addPortList, imageName);
            }

            if (editPortList.size() > 0) {
                // 批量修改
                count = count + batchEditImagePort(editPortList);
            }
        }
        return count;
    }

    /*
    * 新增,镜像,启动参数
    * */
    @Override
    public int batchAddImageCommandArg(List<ImageArgsBean> argsBeanList, String imageName) throws VenusException {
        String sql = " INSERT INTO t_image_command_agrs(" +
                "id," +
                "image," +
                "arg," +
                "serial_number," +
                "create_time," +
                "last_update_time) " +
                "VALUES(?,?,?,?,NOW(),NOW())";
        int[] ii = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(java.sql.PreparedStatement ps, int i) throws SQLException {
                ImageArgsBean argsBean = argsBeanList.get(i);
                ps.setString(1, StringUtil.getUUID());
                ps.setString(2, imageName);
                ps.setString(3, argsBean.getArg());
                ps.setInt(4, argsBean.getSerialNumber());
            }

            @Override
            public int getBatchSize() {
                return argsBeanList.size();
            }
        });
        return ii.length;
    }

    /*
    * 修改,镜像,启动参数
    * */
    @Override
    public int batchEditImageCommandArg(List<ImageArgsBean> argsBeanList) {
        String sql = " UPDATE t_image_command_agrs SET arg = ?,serial_number=?,last_update_time=NOW() WHERE id = ?";
        int[] ii = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(java.sql.PreparedStatement ps, int i) throws SQLException {
                ImageArgsBean argsBean = argsBeanList.get(i);
                ps.setString(1, argsBean.getArg());
                ps.setInt(2, argsBean.getSerialNumber());
                ps.setString(3, argsBean.getId());
                ;

            }

            @Override
            public int getBatchSize() {
                return argsBeanList.size();
            }
        });
        return ii.length;
    }

    /*
    * 删除镜像,启动参数
    * */
    @Override
    public int deleteImageArg(String id) throws VenusException {
        String sql = " DELETE FROM t_image_command_agrs WHERE id = ?";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(id);
        int row = jdbcTemplate.update(sql, objectList.toArray());
        return row;
    }

    /*
    * 处理,镜像,启动参数
    * */
    @Override
    public int handleImageArgs(List<ImageArgsBean> argsBeanList, String imageName) throws VenusException {
        int size = argsBeanList.size();
        List<ImageArgsBean> addImageArgs = new ArrayList<ImageArgsBean>();
        List<ImageArgsBean> editImageArgs = new ArrayList<ImageArgsBean>();
        int count = 0;
        if (size > 0) {
            /*argsBeanList.forEach(imageArgsBean -> {
                String id = imageArgsBean.getId();
                if (StringUtils.isNotBlank(id) && id.length() == 32) {
                    // 修改
                    editImageArgs.add(imageArgsBean);
                } else {
                    // 新增
                    addImageArgs.add(imageArgsBean);
                }
            });*/
            for (int i = 0; i < size; i++) {
                ImageArgsBean imageArgsBean = argsBeanList.get(i);
                String id = imageArgsBean.getId();
                imageArgsBean.setSerialNumber(i);
                if (StringUtils.isNotBlank(id) && id.length() == 32) {
                    // 修改
                    editImageArgs.add(imageArgsBean);
                } else {
                    // 新增
                    addImageArgs.add(imageArgsBean);
                }
            }

            if (addImageArgs.size() > 0) {
                count = count + batchAddImageCommandArg(addImageArgs, imageName);
            }

            if (editImageArgs.size() > 0) {
                count = count + batchEditImageCommandArg(editImageArgs);
            }
        }
        return count;
    }

    /*
    * 新增镜像-环境变量-信息
    * */
    @Override
    public int batchAddImageEnv(List<ImageEnvBean> envBeanList, String imageName) throws VenusException {
        String sql = " INSERT INTO t_image_env(" +
                "id," +
                "image," +
                "env_key," +
                "env_value," +
                "create_time," +
                "last_update_time) " +
                " VALUES(?,?,?,?,NOW(),NOW())";
        Object[] obj = null;
        List<Object[]> objs = new ArrayList<Object[]>();

        for (ImageEnvBean envBean : envBeanList) {
            obj = new Object[4];
            obj[0] = StringUtil.getUUID();
            obj[1] = imageName;
            obj[2] = envBean.getEnvKey();
            obj[3] = envBean.getEnvValue();
            objs.add(obj);
        }
        int[] r = jdbcTemplate.batchUpdate(sql, objs);
        return r.length;
    }

    /*
    * 修改镜像-环境变量-信息
    * */
    @Override
    public int batchEditImageEnv(List<ImageEnvBean> envBeanList) throws VenusException {
        String sql = " UPDATE t_image_env SET " +
                "env_value=?," +
                "last_update_time=NOW() WHERE " +
                "id =? ";
        Object[] objects = null;
        List<Object[]> list = new ArrayList<Object[]>();
        for (ImageEnvBean imageEnvBean : envBeanList) {
            objects = new Object[2];
            objects[0] = imageEnvBean.getEnvValue();
            objects[1] = imageEnvBean.getId();
            list.add(objects);
        }
        int[] r = jdbcTemplate.batchUpdate(sql, list);
        return r.length;
    }

    /*
    * 获取环境变量信息
    * */
    @Override
    public ImageEnvBean getImageEnv(String image, String envKey) {
        String sql = "SELECT " +
                "id," +
                "image," +
                "env_key AS envKey, " +
                "env_value AS envValue " +
                "FROM t_image_env " +
                "WHERE " +
                "image = ? AND " +
                "env_key = ? ";
        List<Object> objectList = new ArrayList<>();
        objectList.add(image);
        objectList.add(envKey);
        ImageEnvBean imageEnvBean = null;
        try {
            imageEnvBean = jdbcTemplate.queryForObject(sql, new RowMapper<ImageEnvBean>() {
                @Override
                public ImageEnvBean mapRow(ResultSet resultSet, int i) throws SQLException {
                    ImageEnvBean envBean = new ImageEnvBean();
                    envBean.setId(resultSet.getString("id"));
                    envBean.setImage(resultSet.getString("image"));
                    envBean.setEnvKey(resultSet.getString("envKey"));
                    envBean.setEnvValue(resultSet.getString("envValue"));
                    return envBean;
                }
            }, objectList.toArray());
        } catch (EmptyResultDataAccessException e) {
            return imageEnvBean;
        }
        return imageEnvBean;
    }

    /*
    * 删除镜像-环境变量-信息
    * */
    @Override
    public int deleteImageEnv(String id) throws VenusException {
        String sql = "DELETE FROM t_image_env WHERE id = ?";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(id);
        int row = jdbcTemplate.update(sql, objectList.toArray());

        return row;
    }

    /*
    * 处理镜像-环境变量信息
    * */
    @Override
    public int handleImageEnv(List<ImageEnvBean> envBeanList, String imageName) throws VenusException {
        int size = envBeanList.size();
        List<ImageEnvBean> addImageEnvList = new ArrayList<>();
        List<ImageEnvBean> editImageEnvList = new ArrayList<>();
        int count = 0;
        if (size > 0) {
            envBeanList.forEach(imageEnvBean -> {
                String id = imageEnvBean.getId();
                String envKey = imageEnvBean.getEnvKey();
                // 判断是否存在相同的数据
                ImageEnvBean imageEnvBean1 = getImageEnv(imageName, envKey);
                if (imageEnvBean1 != null) {
                    editImageEnvList.add(imageEnvBean);
                } else {
                    addImageEnvList.add(imageEnvBean);
                }
            });

            if (addImageEnvList.size() > 0) {
                count = count + batchAddImageEnv(addImageEnvList, imageName);
            }

            if (editImageEnvList.size() > 0) {
                count = count + batchEditImageEnv(editImageEnvList);
            }
        }
        return count;
    }

    /*
    * 新增镜像-配置管理文件卷-信息
    * */
    @Override
    public int batchAddImageConfigVolumes(List<ImageConfigVolumesBean> configVolumesBeanList, String imageName) throws VenusException {
        String sql = "INSERT INTO t_image_config_volumes(" +
                "id," +
                "image," +
                "mouth_path," +
                /*"config_group," +
                "config_files," +*/
                "create_time," +
                "last_update_time) " +
                " VALUES(?,?,?,NOW(),NOW())";
        Object[] objects = null;
        List<Object[]> list = new ArrayList<Object[]>();
        for (ImageConfigVolumesBean volumesBean : configVolumesBeanList) {
            objects = new Object[3];
            objects[0] = StringUtil.getUUID();
            objects[1] = imageName;
            objects[2] = volumesBean.getMouthPath();
            /*objects[3] = volumesBean.getConfigGroup();
            String[] arr = volumesBean.getConfigFiles();
            objects[4] = AppManageConfigBean.appendStr(arr);*/
            list.add(objects);
        }
        int[] rr = jdbcTemplate.batchUpdate(sql, list);
        return rr.length;
    }

    /*
    * 修改镜像-配置管理文件卷-信息,根据ID修改
    * */
    @Override
    public int batchEditImageConfigVolumes(List<ImageConfigVolumesBean> configVolumesBeanList) throws VenusException {
        String sql = " UPDATE t_image_config_volumes SET " +
                "mouth_path=?, " +
                /*"config_group=?, " +
                "config_files=?, " +*/
                " last_update_time=NOW() " +
                "WHERE " +
                "id = ?";
        Object[] objects = null;
        List<Object[]> list = new ArrayList<Object[]>();
        for (ImageConfigVolumesBean volumesBean : configVolumesBeanList) {
            objects = new Object[2];
            objects[0] = volumesBean.getMouthPath();
            /*objects[1] = volumesBean.getConfigGroup();
            String[] arr = volumesBean.getConfigFiles();
            objects[2] = AppManageConfigBean.appendStr(arr);*/
            objects[1] = volumesBean.getId();
            list.add(objects);
        }
        int[] rr = jdbcTemplate.batchUpdate(sql, list);
        return rr.length;
    }

    /*
    * 删除镜像配置文件目录
    * */
    public int deleteImageConfigVolumes(String id) throws VenusException {
        String sql = "DELETE FROM t_image_config_volumes WHERE id = ?";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(id);
        int row = jdbcTemplate.update(sql, objectList.toArray());
        return row;
    }


    /*
    * 处理镜像,配置管理文件卷-信息
    * */
    @Override
    public int handleImageConfigVolumes(List<ImageConfigVolumesBean> configVolumesBeanList, String imageName) throws VenusException {
        int size = configVolumesBeanList.size();
        List<ImageConfigVolumesBean> addVolumesList = new ArrayList<ImageConfigVolumesBean>();
        List<ImageConfigVolumesBean> editVolumesList = new ArrayList<ImageConfigVolumesBean>();
        int count = 0;
        if (size > 0) {
            configVolumesBeanList.forEach(imageConfigVolumesBean -> {
                String id = imageConfigVolumesBean.getId();
                if (id.length() == 32) {
                    // 修改
                    editVolumesList.add(imageConfigVolumesBean);
                } else {
                    // 新增
                    addVolumesList.add(imageConfigVolumesBean);
                }
            });

            if (addVolumesList.size() > 0) {
                count = count + batchAddImageConfigVolumes(addVolumesList, imageName);
            }

            if (editVolumesList.size() > 0) {
                count = count + batchEditImageConfigVolumes(editVolumesList);
            }
        }
        return count;
    }

    /*
    * 新增镜像-高可用信息
    * */
    @Override
    public int addImageHA(ImageHighAvailabilityBean imageHighAvailabilityBean, String imageName) throws VenusException {
        String sql = "INSERT INTO t_image_high_availability(" +
                "id," +
                "image," +
                "type," +
                "port," +
                "initial_delay_seconds," +
                "period_seconds," +
                "timeout_seconds," +
                "path," +
                "create_time," +
                "last_update_time) " +
                " VALUES(?,?,?,?,?,?,?,?,NOW(),NOW())";

        int type = imageHighAvailabilityBean.getType();
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(StringUtil.getUUID());
        objectList.add(imageName);
        objectList.add(imageHighAvailabilityBean.getType());
        String path = "";
        int port = 0;
        int initialDelaySeconds = 0;
        int periodSeconds = 0;
        int timeoutSeconds = 0;
        if (type > 1) {
            port = imageHighAvailabilityBean.getPort();
            initialDelaySeconds = imageHighAvailabilityBean.getInitialDelaySeconds();
            periodSeconds = imageHighAvailabilityBean.getPeriodSeconds();
            timeoutSeconds = imageHighAvailabilityBean.getTimeoutSeconds();
            if (type == 2) {
                path = imageHighAvailabilityBean.getPath();
            }
        }
        objectList.add(port);
        objectList.add(initialDelaySeconds);
        objectList.add(periodSeconds);
        objectList.add(timeoutSeconds);
        objectList.add(path);
        int row = jdbcTemplate.update(sql, objectList.toArray());
        return row;
    }

    /*
    * 修改镜像-高可用信息
    * */
    @Override
    public int editImageHA(ImageHighAvailabilityBean imageHighAvailabilityBean) throws VenusException {
        String sql = " UPDATE t_image_high_availability SET " +
                "type=?," +
                "port=?," +
                "initial_delay_seconds=?," +
                "period_seconds=?," +
                " timeout_seconds=?," +
                "path=?," +
                "last_update_time=NOW() WHERE " +
                "id = ? ";
        List<Object> objectList = new ArrayList<Object>();
        int type = imageHighAvailabilityBean.getType();
        objectList.add(imageHighAvailabilityBean.getType());
        int port = 0;
        int initial_delay_seconds = 0;
        int period_seconds = 0;
        int timeout_seconds = 0;
        String path = "";
        if (type > 1) {
            port = imageHighAvailabilityBean.getPort();
            initial_delay_seconds = imageHighAvailabilityBean.getInitialDelaySeconds();
            period_seconds = imageHighAvailabilityBean.getPeriodSeconds();
            timeout_seconds = imageHighAvailabilityBean.getTimeoutSeconds();
            if (type == 2) {
                path = imageHighAvailabilityBean.getPath();
            }
        }
        objectList.add(port);
        objectList.add(initial_delay_seconds);
        objectList.add(period_seconds);
        objectList.add(timeout_seconds);
        objectList.add(path);
        objectList.add(imageHighAvailabilityBean.getId());
        int row = jdbcTemplate.update(sql, objectList.toArray());
        return row;
    }

    /*
    * 删除镜像,参数信息,根据镜像的ID,参数类型: port,env
    * */
    @Override
    public int deleteImageParam(String id, String paramType) throws VenusException {
        int row = 0;
        if ("port".equals(paramType)) {
            row = deleteImagePort(id);
        } else if ("env".equals(paramType)) {
            row = deleteImageEnv(id);
        } else if ("commandArg".equals(paramType)) {
            row = deleteImageArg(id);
        } else if ("configMap".equals(paramType)) {
            row = deleteImageConfigVolumes(id);
        }
        return row;
    }

    /*
    * 校验k8s里面的应用名称是否重复
    * */
    @Override
    public int validateAppNameKube(String appNameKube) throws VenusException {
        String sql = "SELECT id FROM t_app_manage WHERE app_name_kube = ? ";
        List<Object> objectList = new ArrayList<>();
        objectList.add(appNameKube);
        Map<String, Object> map = new HashMap<>();
        try {
            map = jdbcTemplate.queryForMap(sql, objectList.toArray());
        } catch (EmptyResultDataAccessException e) {
            return 0;
        }
        if (map.size() > 0) {
            return 1;
        }

        return 0;
    }

    ////////////////////////////////////////////////////根据选择的镜像部署应用////////////////////////////////////////////////////////////////////////////////

    /*
    * 得到一对label标签
    * */
    @Override
    public Map<String, String> getLabelMap(String labelKey, String labelValue) throws VenusException {
        Map<String, String> appLabelMap = new HashMap<String, String>();
        appLabelMap.put(labelKey, labelValue);
        return appLabelMap;
    }

    /*
    * 得到请求内存,最小,最大,资源-map
    * */
    @Override
    public Map<String, Quantity> getMemoryResourcesMap(String value) throws VenusException {
        Map<String, Quantity> requestsMap = new HashMap<String, Quantity>();
        Quantity memory_R = new QuantityBuilder()
                .withAmount(value)
                .build();
        requestsMap.put("memory", memory_R);
        return requestsMap;
    }

    /*
    * 得到容器端口列表
    * */
    @Override
    public List<ContainerPort> getContainerPortList(List<ImagePortBean> portList) throws VenusException {
        List<ContainerPort> containerPortList = new ArrayList<ContainerPort>();
        int size = portList.size();
        for (int i = 0; i < size; i++) {
            ImagePortBean imagePortBean = portList.get(i);
            String name = AppManageConfigBean.CONTAINER_PORT_NAME + i;
            ContainerPort containerPort = new ContainerPortBuilder()
                    .withName(name)
                    .withContainerPort(imagePortBean.getPort())
                    .build();
            containerPortList.add(containerPort);
        }
        return containerPortList;
    }

    /*
    * 得到环境变量列表
    * */
    @Override
    public List<EnvVar> getEnvVarList(List<ImageEnvBean> envBeanList) throws VenusException {
        List<EnvVar> envVarList = new ArrayList<EnvVar>();
        if (envBeanList.size() > 0) {
            envBeanList.forEach(imageEnvBean -> {
                EnvVar envVar = new EnvVarBuilder()
                        .withName(imageEnvBean.getEnvKey())
                        .withValue(imageEnvBean.getEnvValue())
                        .build();
                envVarList.add(envVar);
            });
        }
        return envVarList;
    }

    /*
    * 得到 VolumeMount
    * */
    @Override
    public VolumeMount getVolumeMount(String name, String mouthPath) throws VenusException {
        VolumeMount volumeMount = new VolumeMountBuilder()
                .withMountPath(mouthPath)
                .withReadOnly(false)
                .withName(name)
                .build();
        return volumeMount;
    }

    /*
    * 得到容器-配置文件挂载卷列表
    * */
    @Override
    public List<VolumeMount> getConfigVolumeMountList(List<ImageConfigVolumesBean> volumesBeanList, List<VolumeMount> volumeMountList) throws VenusException {
        int size = volumesBeanList.size();
        for (int i = 0; i < size; i++) {
            ImageConfigVolumesBean volumesBean = volumesBeanList.get(i);
            String name = AppManageConfigBean.CONFIGMAP_VOLUME_NAME + i;
            VolumeMount volumeMount = getVolumeMount(name, volumesBean.getMouthPath());
            volumeMountList.add(volumeMount);
        }
        return volumeMountList;
    }

    /*
    * 得到,StatefulSet,有状态,持久化挂载卷列表
    * */
    @Override
    public List<VolumeMount> getStatefulSetVolumeMountList(List<ImageStatefulSetPVCBean> statefulSetPVCBeanList, List<VolumeMount> volumeMountList) throws VenusException {
        int size = statefulSetPVCBeanList.size();
        for (int i = 0; i < size; i++) {
            ImageStatefulSetPVCBean statefulSetPVCBean = statefulSetPVCBeanList.get(i);
            String name = AppManageConfigBean.STATEFULSET_PVC_VOLUME_NAME + i;
            VolumeMount volumeMount = getVolumeMount(name, statefulSetPVCBean.getMouthPath());
            volumeMountList.add(volumeMount);
        }
        return volumeMountList;
    }

    /*
    * 得到,deployment,持久化挂载卷列表
    * */
    @Override
    public List<VolumeMount> getDeploymentVolumeMountList(List<ImageDeploymentPVCBean> deploymentPVCBeanList, List<VolumeMount> volumeMountList) throws VenusException {
        int size = deploymentPVCBeanList.size();
        for (int i = 0; i < size; i++) {
            ImageDeploymentPVCBean deploymentPVCBean = deploymentPVCBeanList.get(i);
            String name = AppManageConfigBean.DEPLOYMENT_PVC_VOLUME_NAME + i;
            VolumeMount volumeMount = getVolumeMount(name, deploymentPVCBean.getMouthPath());
            volumeMountList.add(volumeMount);
        }
        return volumeMountList;
    }

    /*
    * 得到容器-配置文件卷列表
    * */
    @Override
    public List<Volume> getConfigVolumeList(List<ImageConfigVolumesBean> volumesBeanList, List<Volume> volumeList) throws VenusException {
        int size = volumesBeanList.size();
        for (int i = 0; i < size; i++) {
            ImageConfigVolumesBean configVolumesBean = volumesBeanList.get(i);
            String name = AppManageConfigBean.CONFIGMAP_VOLUME_NAME + i;
            // 配置文件列表
            String[] configFiles = configVolumesBean.getConfigFiles();
            List<KeyToPath> keyToPathList = getKeyToPathList(configFiles);
            Volume configMapVolume = new VolumeBuilder()
                    .withName(name) // 卷名
                    .withNewConfigMap() // 配置组名称
                    .withName(configVolumesBean.getConfigGroup())
                    .withItems(keyToPathList)
                    .endConfigMap()
                    .build();
            volumeList.add(configMapVolume);
        }
        return volumeList;
    }

    /*
    * 得到,StatefulSet,有状态,持久化卷列表
    * */
    @Override
    public List<PersistentVolumeClaim> getStatefulSetVolumeList(List<ImageStatefulSetPVCBean> statefulSetPVCBeanList, String appNameKube) throws VenusException {
        List<PersistentVolumeClaim> persistentVolumeClaimList = new ArrayList<PersistentVolumeClaim>();
        Map<String, String> annoeationsMap = getLabelMap(AppManageConfigBean.ANNOEATIONS_Map_KEY, AppManageConfigBean.ANNOEATIONS_Map_VALUE);
        int size = statefulSetPVCBeanList.size();
        for (int i = 0; i < size; i++) {
            ImageStatefulSetPVCBean statefulSetPVCBean = statefulSetPVCBeanList.get(i);
            String name = AppManageConfigBean.STATEFULSET_PVC_VOLUME_NAME + i;
            // 申请的pvc大小
            int capacity = statefulSetPVCBean.getCapacity();
            // 挂载目录
            String mouthPath = statefulSetPVCBean.getMouthPath();
            String amount = String.valueOf(capacity) + AppManageConfigBean.Mi;

            // 标签
            annoeationsMap.put(AppManageConfigBean.APP_LABEL_KEY, appNameKube);
            annoeationsMap.put(AppManageConfigBean.MOUTH_PATH_KEY, mouthPath);

            // 申请大小map
            Map<String, Quantity> pvc_Q = new HashMap<String, Quantity>();
            Quantity quantity = new QuantityBuilder()
                    .withAmount(amount)
                    .build();
            pvc_Q.put("storage", quantity);

            // pvc卷
            PersistentVolumeClaim persistentVolumeClaim = new PersistentVolumeClaimBuilder()
                    .withNewMetadata()
                    .withName(name)
                    .withAnnotations(annoeationsMap)
                    .endMetadata()
                    .withNewSpec()
                    .withAccessModes("ReadWriteOnce")
                    .withNewResources()
                    .withRequests(pvc_Q)
                    .endResources()
                    .endSpec()
                    .build();
            persistentVolumeClaimList.add(persistentVolumeClaim);
        }
        return persistentVolumeClaimList;
    }

    /*
    * 得到,deployment,持久化卷列表
    * */
    @Override
    public List<Volume> getDeploymentVolumeList(List<ImageDeploymentPVCBean> deploymentPVCBeanList, List<Volume> volumeList) throws VenusException {
        int size = deploymentPVCBeanList.size();
        for (int i = 0; i < size; i++) {
            ImageDeploymentPVCBean deploymentPVCBean = deploymentPVCBeanList.get(i);
            String name = AppManageConfigBean.DEPLOYMENT_PVC_VOLUME_NAME + i;
            String pvc = deploymentPVCBean.getPvc();
            Volume pvcVolume = new VolumeBuilder()
                    .withName(name) // 卷名
                    .withNewPersistentVolumeClaim()
                    .withClaimName(pvc) // pvc 名称
                    .endPersistentVolumeClaim()
                    .build();
            volumeList.add(pvcVolume);
        }
        return volumeList;
    }

    /*
    * 得到,配置文件key-path list
    * */
    @Override
    public List<KeyToPath> getKeyToPathList(String[] configFiles) throws VenusException {
        List<KeyToPath> keyToPathList = new ArrayList<KeyToPath>();
        for (String configFile : configFiles) {
            KeyToPath keyToPath = new KeyToPathBuilder()
                    .withKey(configFile)
                    .withPath(configFile)
                    .build();
            keyToPathList.add(keyToPath);
        }
        return keyToPathList;
    }

    /*
    * 得到镜像,启动参数
    * */
    @Override
    public List<String> getArgsList(List<ImageArgsBean> argsBeanList) throws VenusException {
        int size = argsBeanList.size();
        List<String> list = new ArrayList<String>();
        if (size > 0) {
            argsBeanList.forEach(imageArgsBean -> {
                String arg = imageArgsBean.getArg();
                if (StringUtils.isNotBlank(arg)) {
                    list.add(arg);
                }
            });

        }
        return list;
    }

    /*
    * 高可用: http
    * */
    @Override
    public Probe getHttpProbe(ImageHighAvailabilityBean highAvailabilityBean) throws VenusException {
        Probe probe = new ProbeBuilder()
                .withNewHttpGet()
                .withNewPort()
                .withIntVal(highAvailabilityBean.getPort())
                .endPort()
                .endHttpGet()
                .withInitialDelaySeconds(highAvailabilityBean.getInitialDelaySeconds())
                .withPeriodSeconds(highAvailabilityBean.getPeriodSeconds())
                .withTimeoutSeconds(highAvailabilityBean.getTimeoutSeconds())
                .build();
        return probe;
    }

    /*
    * 高可用: tcp
    * */
    @Override
    public Probe getTcpProbe(ImageHighAvailabilityBean highAvailabilityBean) throws VenusException {
        Probe probe = new ProbeBuilder()
                .withNewTcpSocket()
                .withNewPort(highAvailabilityBean.getPort())
                .endTcpSocket()
                .withInitialDelaySeconds(highAvailabilityBean.getInitialDelaySeconds())
                .withPeriodSeconds(highAvailabilityBean.getPeriodSeconds())
                .withTimeoutSeconds(highAvailabilityBean.getTimeoutSeconds())
                .build();
        return probe;
    }

    /*
    * 根据空间名称,得到该空间所属的物理分组
    * */
    @Override
    public String getPhysicalGroup(String namespace) throws VenusException {
        String sql = "SELECT DISTINCT " +
                "pg.name_en " +
                "FROM t_namespace n " +
                "LEFT JOIN t_physical_group pg " +
                "ON n.physical_group = pg.id " +
                "WHERE n.kube_name = ?";
        List<Object> objectList = new ArrayList<Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        objectList.add(namespace);
        try {
            map = jdbcTemplate.queryForMap(sql, objectList.toArray());
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
        if (map.size() > 0) {
            return (String) map.get("name_en");
        }
        return null;
    }

    /*
    * 部署,无状态的应用,deployment
    * */
    @Override
    public boolean deploymentApp(ImageDataBean imageDataBean) throws VenusException {
        try {
            // 部署空间
            String namespace = imageDataBean.getNamespace();
            // 镜像基础信息
            ImageBaseBean imageBaseBean = imageDataBean.getImageBase();
            String appNameKube = imageBaseBean.getAppNameKube();
            String image = AppManageConfigBean.getImageName(imageBaseBean.getImage(), imageBaseBean.getImageVersion(), appManageConfigBean.getHarborUrl());
            int replicas = imageBaseBean.getReplicas();
            //String requestsMemory = imageBaseBean.getRequestsMemory();
            String requestsMemory = "100Mi";
            String limitsMemory = imageBaseBean.getLimitsMemory();
            String limitsCPU = imageBaseBean.getLimitsCPU();


            // 端口信息
            List<ImagePortBean> portList = imageDataBean.getImagePortList();
            // 环境变量信息
            List<ImageEnvBean> envBeanList = imageDataBean.getImageEnvList();
            // 配置文件信息
            List<ImageConfigVolumesBean> configVolumesBeanList = imageDataBean.getImageConfigVolumesList();
            // 持久化卷信息
            List<ImageDeploymentPVCBean> deploymentPVCBeanList = imageDataBean.getImageDeploymentPVCList();
            // 高可用信息
            ImageHighAvailabilityBean highAvailabilityBean = imageDataBean.getImageHA();


            // 1: 标签
            Map<String, String> appLabelMap = getLabelMap(AppManageConfigBean.APP_LABEL_KEY, appNameKube);

            // 2: 滚动升级的规则
            DeploymentStrategy deploymentStrategy = k8sManageService.getDeploymentStrategy();

            // 3: 得到物理分组名称
            String physicalGroup = getPhysicalGroup(namespace);
            if (StringUtils.isBlank(physicalGroup))
                throw new VenusException(VenusResponseStatus.APP_DEPLOY_EXCEPTION, namespace + AppManageConfigBean.APP_DEPLOY_EXCEPTION_NOT_FOUND_PHYSICAL_GROUP);
            Map<String, String> nodeSelectorMap = getLabelMap(AppManageConfigBean.APP_LABEL_PHYSICAL_GROUP_KEY, physicalGroup);

            // 4: 拉取镜像的秘钥
            LocalObjectReference localObjectReference = k8sManageService.getLocalObjectReference(AppManageConfigBean.PULL_IMAGE_SECRET);

            // 5: 应用请求的最小内存
            Map<String, Quantity> memoryRequestsMap = getMemoryResourcesMap(requestsMemory);
            Quantity cpu_R = new QuantityBuilder()
                    .withAmount("100m")
                    .build();
            memoryRequestsMap.put("cpu", cpu_R);

            // 6: 应用请求的最大内存
            Map<String, Quantity> memoryLimitMap = getMemoryResourcesMap(limitsMemory);
            Quantity cpu_L = new QuantityBuilder()
                    .withAmount(limitsCPU)
                    .build();
            memoryLimitMap.put("cpu", cpu_L);

            // 7: 端口
            List<ContainerPort> containerPortList = getContainerPortList(portList);

            // 8: 环境变量
            List<EnvVar> envVarList = getEnvVarList(envBeanList);

            // 9: 容器挂载卷配置
            List<VolumeMount> volumeMountList = new ArrayList<VolumeMount>();
            volumeMountList = getConfigVolumeMountList(configVolumesBeanList, volumeMountList);
            volumeMountList = getDeploymentVolumeMountList(deploymentPVCBeanList, volumeMountList);

            // 10: 应用高可用信息
            int haType = highAvailabilityBean.getType();

            Probe haProbe = null;
            if (haType == 2) {
                // http
                haProbe = getHttpProbe(highAvailabilityBean);
            } else if (haType == 3) {
                // tcp
                haProbe = getTcpProbe(highAvailabilityBean);
            }

            // 11: 配置卷
            List<Volume> volumeList = new ArrayList<Volume>();
            volumeList = getConfigVolumeList(configVolumesBeanList, volumeList);
            volumeList = getDeploymentVolumeList(deploymentPVCBeanList, volumeList);

            // 12; 容器
            Container container = new ContainerBuilder()
                    .withName(appNameKube)
                    .withImage(image)
                    .withImagePullPolicy(imageBaseBean.getImagePullPolicy())
                    .withNewResources()
                    .withRequests(memoryRequestsMap)
                    .withLimits(memoryLimitMap)
                    .endResources()
                    .withEnv(envVarList)
                    .withPorts(containerPortList)
                    .withVolumeMounts(volumeMountList)
                    .build();
            // 添加高可用探针
            if (haProbe != null) {
                container.setLivenessProbe(haProbe);
                container.setReadinessProbe(haProbe);
            }


            // 容器启动命令
            int startCommand = imageBaseBean.getStartCommand();
            if (startCommand == 2) {
                String command = imageBaseBean.getCommand();
                List<String> commandList = new ArrayList<String>();
                commandList.add(command);
                container.setCommand(commandList);
            }

            // 容器启动参数
            List<ImageArgsBean> argsBeanList = imageDataBean.getCommandArgs();
            if (argsBeanList.size() > 0) {
                List<String> argsList = getArgsList(argsBeanList);
                container.setArgs(argsList);
            }

            Deployment deployment = new DeploymentBuilder()
                    .withNewMetadata()
                    .withName(appNameKube)
                    .withNamespace(namespace)
                    .endMetadata()
                    .withNewSpec()
                    .withReplicas(replicas)
                    .withNewSelector()
                    .withMatchLabels(appLabelMap)
                    .endSelector()
                    .withNewStrategy()
                    .withNewRollingUpdate()
                    .withNewMaxSurge(1)
                    .withNewMaxUnavailable(1)
                    .endRollingUpdate()
                    .endStrategy()
                    .withMinReadySeconds(30)
                    .withNewTemplate()
                    .withNewMetadata()
                    .withLabels(appLabelMap)
                    .endMetadata()
                    .withNewSpec()
                    .withNodeSelector(nodeSelectorMap)
                    .withImagePullSecrets(localObjectReference)
                    .withContainers(container)
                    .withVolumes(volumeList)
                    .endSpec()
                    .endTemplate()
                    .endSpec()
                    .build();


            // 部署
            deployment = k8sManageService.createDployment(deployment, namespace);
            if (deployment != null) {
                // 标记pvc卷为已经使用
                for (ImageDeploymentPVCBean deploymentPVCBean : deploymentPVCBeanList) {
                    String pvcName = deploymentPVCBean.getPvc();
                    String mountPath = deploymentPVCBean.getMouthPath();
                    // 设置pvc卷标签
                    k8sStorageService.setPersistentVolumeClaim(pvcName, namespace, appNameKube, mountPath);
                }
                return true;
            }
        } catch (Exception e) {
            throw new VenusException(VenusResponseStatus.K8S_EXCEPTION, "k8s异常,部署应用失败!");
        }
        return false;
    }

    /*
    * 新增记录到数据库
    * */
    @Override
    public int addDeployApp(ImageBaseBean imageBaseBean, String namespace) throws VenusException {
        String sql = "INSERT INTO t_app_manage(" +
                "id," +
                "app_name," +
                "app_name_kube," +
                "app_kind," +
                "image_name," +
                "image_version," +
                "described," +
                "namespace," +
                "deploy_type," +
                "create_time," +
                "last_update_time) " +
                "VALUES(?,?,?,?,?,?,?,?,?,NOW(),NOW())";
        List<Object> objectList = new ArrayList<Object>();
        objectList.add(StringUtil.getUUID());
        objectList.add(imageBaseBean.getAppName());
        objectList.add(imageBaseBean.getAppNameKube());
        objectList.add(imageBaseBean.getAppKind());
        objectList.add(imageBaseBean.getImage());
        objectList.add(imageBaseBean.getImageVersion());
        objectList.add(imageBaseBean.getDescribed());
        objectList.add(namespace);
        objectList.add(1);
        int row = jdbcTemplate.update(sql, objectList.toArray());
        return row;
    }

    /*
    * 处理应用服务
    * */
    @Override
    public boolean handelService(List<ImagePortBean> portBeanList, String appNameKube, String namespace) throws VenusException {
        // 对内服务
        Map<String, ImagePortBean> portBeanHashMap = new HashMap<String, ImagePortBean>();
        int size = portBeanList.size();
        boolean flag = false;
        for (int i = 0; i < size; i++) {
            ImagePortBean portBean = portBeanList.get(i);
            String portName = AppManageConfigBean.CONTAINER_PORT_NAME + i;
            boolean isVisible = portBean.isVisible();
            String protocol = portBean.getProtocol();
            if (isVisible) {
                if ("tcp".equals(protocol)) {
                    flag = createOutTcpService(portBean, portName, appNameKube, namespace);
                } else if ("http".equals(protocol)) {
                    flag = createOutHttpService(portBean, portName, appNameKube, namespace, i);
                }
            } else {
                portBeanHashMap.put(portName, portBean);
            }
        }

        if (portBeanHashMap.size() > 0) {
            flag = createInService(portBeanHashMap, appNameKube, namespace);
        }
        return flag;
    }

    /*
    * 创建内部服务
    * */
    public boolean createInService(Map<String, ImagePortBean> imagePortBeanMap, String appNameKube, String namespace) throws VenusException {
        Map<String, String> appMap = getLabelMap(AppManageConfigBean.APP_LABEL_KEY, appNameKube);
        String serviceName = AppManageConfigBean.getServiceName(appNameKube) + "-in";
        List<ServicePort> servicePortList = new ArrayList<ServicePort>();
        for (Map.Entry<String, ImagePortBean> map : imagePortBeanMap.entrySet()) {
            ImagePortBean portBean = map.getValue();

            // 获得服务名
            try {
                if (portBean.getServiceNameType().equals(AppManageConfigBean.SERVICE_PORT_TYPE_APPOINT) && StringUtils.isNotBlank(portBean.getServiceName())) {
                    serviceName = portBean.getServiceName();
                }
            } catch (NullPointerException n) {
            }

            String name = map.getKey();
            ServicePort servicePort = new ServicePortBuilder()
                    .withPort(portBean.getPort())
                    .withNewTargetPort()
                    .withIntVal(portBean.getPort())
                    .endTargetPort()
                    .withName(name)
                    .build();
            if (portBean.getProtocol().equals("tcp")) {
                servicePort.setProtocol("TCP");
            }
            servicePortList.add(servicePort);
        }

        // 添加注解
        Map<String, String> annotationsMap = new HashMap<String, String>();
        annotationsMap.put(AppManageConfigBean.SERVICE_TYPE, AppManageConfigBean.SERVICE_TYPE_IN);

        Service service = new ServiceBuilder()
                .withNewMetadata()
                .withName(serviceName)
                .withNamespace(namespace)
                .withLabels(appMap)
                .withAnnotations(annotationsMap)
                .endMetadata()
                .withNewSpec()
                .withClusterIP(AppManageConfigBean.NONE)
                .withSelector(appMap)
                .withPorts(servicePortList)
                .endSpec()
                .build();

        service = k8sManageService.createService(service, namespace);

        if (service == null) {
            return false;
        }
        return true;
    }

    /*
    * 创建tcp对外服务
    * */
    public boolean createOutTcpService(ImagePortBean portBean, String portName, String appNameKube, String namespace) throws VenusException {
        Map<String, String> appMap = getLabelMap(AppManageConfigBean.APP_LABEL_KEY, appNameKube);
        String serviceName = AppManageConfigBean.getServiceName(appNameKube) + "-" + portBean.getPort() + "-tcp";
        int nodePort = portBean.getNodePort();

        // 获得服务名称
        try {
            if (portBean.getServiceNameType().equals(AppManageConfigBean.SERVICE_PORT_TYPE_APPOINT) && StringUtils.isNotBlank(portBean.getServiceName())) {
                serviceName = portBean.getServiceName();
            }
        } catch (NullPointerException n) {
        }

        List<ServicePort> servicePortList = new ArrayList<ServicePort>();
        ServicePort servicePort = new ServicePortBuilder()
                .withPort(portBean.getPort())
                .withNewTargetPort()
                .withIntVal(portBean.getPort())
                .endTargetPort()
                .withProtocol(portBean.getProtocol().toUpperCase())
                .withName(portName)
                .build();

        // 是否指定端口
        if (AppManageConfigBean.SERVICE_PORT_TYPE_APPOINT.equals(portBean.getPortType()) && nodePort > 0) {
            servicePort.setNodePort(nodePort);
        }

        // 添加服务注解
        Map<String, String> annotationsMap = new HashMap<String, String>();
        annotationsMap.put(AppManageConfigBean.SERVICE_TYPE, AppManageConfigBean.SERVICE_TYPE_TCP);

        servicePortList.add(servicePort);

        Service service = new ServiceBuilder()
                .withNewMetadata()
                .withName(serviceName)
                .withNamespace(namespace)
                .withLabels(appMap)
                .withAnnotations(annotationsMap)
                .endMetadata()
                .withNewSpec()
                .withType(AppManageConfigBean.SERVICE_PORT_TYPE_NODEPORT)
                .withSelector(appMap)
                .withPorts(servicePortList)
                .endSpec()
                .build();

        service = k8sManageService.createService(service, namespace);

        if (service == null) {
            return false;
        }
        return true;
    }

    /*
    * 创建对外的http服务,同时创建ingress
    * */
    public boolean createOutHttpService(ImagePortBean portBean, String portName, String appNameKube, String namespace, int portIndex) throws VenusException {
        Map<String, String> appMap = getLabelMap(AppManageConfigBean.APP_LABEL_KEY, appNameKube);
        String serviceName = AppManageConfigBean.getServiceName(appNameKube) + "-" + portBean.getPort() + "-http";

        // 获得服务名称
        try {
            if (portBean.getServiceNameType().equals(AppManageConfigBean.SERVICE_PORT_TYPE_APPOINT) && StringUtils.isNotBlank(portBean.getServiceName())) {
                serviceName = portBean.getServiceName();
            }
        } catch (NullPointerException n) {
        }


        List<ServicePort> servicePortList = new ArrayList<ServicePort>();
        ServicePort servicePort = new ServicePortBuilder()
                .withPort(portBean.getPort())
                .withNewTargetPort()
                .withIntVal(portBean.getPort())
                .endTargetPort()
                .withName(portName)
                .build();
        servicePortList.add(servicePort);

        // 添加服务注解
        Map<String, String> annotationsMap = new HashMap<String, String>();
        annotationsMap.put(AppManageConfigBean.SERVICE_TYPE, AppManageConfigBean.SERVICE_TYPE_HTTP);

        Service service = new ServiceBuilder()
                .withNewMetadata()
                .withName(serviceName)
                .withNamespace(namespace)
                .withLabels(appMap)
                .withAnnotations(annotationsMap)
                .endMetadata()
                .withNewSpec()
                .withClusterIP(AppManageConfigBean.NONE)
                .withSelector(appMap)
                .withPorts(servicePortList)
                .endSpec()
                .build();

        service = k8sManageService.createService(service, namespace);

        if (service != null) {
            // 创建ingress
            String ingressName = appNameKube + "-" + (int) ((Math.random() * 9 + 1) * 10000) + "-" + portBean.getPort() + "-" + "ingress";
            String domainName = portBean.getDomainName();
            // 是否动态生成域名
            if (AppManageConfigBean.SERVICE_PORT_TYPE_DYNAMIC.equals(portBean.getDomainNameType())) {
                domainName = AppManageConfigBean.createDomainName(namespace, appNameKube, portIndex);
            }

            // 创建ingress
            Ingress ingress = k8sManageService.createIngress(ingressName, namespace, appNameKube, domainName, serviceName, portBean.getPort());
            if (ingress == null) {
                // 失败
                return false;
            } else {
                // 新增域名记录到数据库
                addDomainName(namespace, appNameKube, serviceName, ingressName, domainName, portBean.getPort());
            }
        }
        return true;
    }

    /*
    * 创建service
    * */
    @Override
    public boolean createService(List<ImagePortBean> portBeanList, String appNameKube, String namespace) throws VenusException {
        Map<String, String> appMap = getLabelMap(AppManageConfigBean.APP_LABEL_KEY, appNameKube);
        String serviceName = AppManageConfigBean.getServiceName(appNameKube);
        int size = portBeanList.size();
        if (size > 0) {
            List<ServicePort> servicePortList = new ArrayList<ServicePort>();
            boolean isVisible = false;
            for (int i = 0; i < size; i++) {
                ImagePortBean portBean = portBeanList.get(i);
                int port = portBean.getPort();
                int nodePort = (Integer) portBean.getNodePort();
                String portType = portBean.getPortType();
                String name = AppManageConfigBean.CONTAINER_PORT_NAME + i;
                ServicePort servicePort = new ServicePortBuilder()
                        .withPort(port)
                        .withNewTargetPort()
                        .withIntVal(port)
                        .endTargetPort()
                        .withName(name)
                        .build();
                // 是否指定端口
                if (portBean.isVisible()) {
                    isVisible = true;
                    if (AppManageConfigBean.SERVICE_PORT_TYPE_APPOINT.equals(portType) && nodePort > 0) {
                        servicePort.setNodePort(nodePort);
                    }
                }

                servicePortList.add(servicePort);
            }


            Service service = new ServiceBuilder()
                    .withNewMetadata()
                    .withName(serviceName)
                    .withNamespace(namespace)
                    .withLabels(appMap)
                    .endMetadata()
                    .withNewSpec()
                    .withSelector(appMap)
                    .withPorts(servicePortList)
                    .endSpec()
                    .build();

            // 是否以nodeport方式对外服务
            if (isVisible) {
                service.getSpec().setType(AppManageConfigBean.SERVICE_PORT_TYPE_NODEPORT);
            } else {
                // 不设置集群ID
                service.getSpec().setClusterIP(AppManageConfigBean.NONE);
            }

            // 创建
            service = k8sManageService.createService(service, namespace);

            if (service != null) {
                return true;
            }
        }

        return false;
    }



    /*
    * 创建service2 lcy 2018/4/2
    * */
    @Override
    public boolean createService2(ServiceBean serviceBean) throws VenusException{
        List<ServicePortBean> servicePortBeans=serviceBean.getServicePorts();
        int size = servicePortBeans.size();
        if (size > 0) {
            List<ServicePort> servicePortList = new ArrayList<ServicePort>();
            String type=serviceBean.getType();
            for (int i = 0; i < size; i++) {
                ServicePortBean servicePortBean = servicePortBeans.get(i);
                int port = servicePortBean.getPort();
                int nodePort = servicePortBean.getNodePort();
                int targetPort=servicePortBean.getTargetPort();
                boolean nodePortAutoCreate=servicePortBean.isNodePortAutoCreate();
                String prtocal=servicePortBean.getProtocal();
                String name = prtocal.toLowerCase()+"-"+StringUtil.getUUID();
                ServicePort servicePort = new ServicePortBuilder()
                        .withName(name)
                        .withProtocol(prtocal)
                        .withPort(port)
                        .withNewTargetPort()
                        .withIntVal(targetPort)
                        .endTargetPort()
                        .build();
                // 是否指定端口
                if (AppManageConfigBean.SERVICE_PORT_TYPE_NODEPORT.equals(type)&&!nodePortAutoCreate) {
                    servicePort.setNodePort(nodePort);
                }
                servicePortList.add(servicePort);
            }
            Service service = null;
            if((!AppManageConfigBean.SERVICE_PORT_TYPE_NODEPORT.equals(type))){
                service = new ServiceBuilder()
                        .withNewMetadata()
                        .withName(serviceBean.getName())
                        .withNamespace(serviceBean.getNamespace())
                        .withLabels(serviceBean.getLabels())
                        .endMetadata()
                        .withNewSpec()
                        .withSelector(serviceBean.getSelectors())
                        .withPorts(servicePortList)
                        .withType(type)
                        //.withClusterIP(AppManageConfigBean.NONE)
                        .withSessionAffinity(serviceBean.getSessionAffinity())
                        .endSpec()
                        .build();
            }else{
                service = new ServiceBuilder()
                        .withNewMetadata()
                        .withName(serviceBean.getName())
                        .withNamespace(serviceBean.getNamespace())
                        .withLabels(serviceBean.getLabels())
                        .endMetadata()
                        .withNewSpec()
                        .withSelector(serviceBean.getSelectors())
                        .withPorts(servicePortList)
                        .withType(type)
                        //.withClusterIP("")
                        .withSessionAffinity(serviceBean.getSessionAffinity())
                        .endSpec()
                        .build();
            }
            // 创建
            //service = k8sManageService.createService(service, serviceBean.getNamespace());
            service = k8sManageService.createOrUpdateService(serviceBean.getNamespace(),service);
            if (service != null) {
                return true;
            }
        }
        return false;
    }

    /*
    * 删除service
    * */
    @Override
    public boolean deleteService(String appNameKube, String namespace) throws VenusException {
        //String serviceName = AppManageConfigBean.getServiceName(appNameKube);
        //boolean flag = k8sManageService.deleteService(serviceName,namespace);
        Map<String, String> appMap = getLabelMap(AppManageConfigBean.APP_LABEL_KEY, appNameKube);
        boolean flag = k8sManageService.deleteServiceByLabels(appMap, namespace);
        return flag;
    }

    /*
    * 根据服务名称删除服务
    * */
    @Override
    public boolean deleteServiceByName(String namespace, String serviceName) throws VenusException {
        boolean flag = k8sManageService.deleteService(serviceName, namespace);
        return flag;
    }

    /*
    * 部署,有状态的应用,statefulset
    * */
    @Override
    public boolean statefulSetApp(ImageDataBean imageDataBean) throws VenusException {
        // 部署空间
        String namespace = imageDataBean.getNamespace();
        // 镜像基础信息
        ImageBaseBean imageBaseBean = imageDataBean.getImageBase();
        String appNameKube = imageBaseBean.getAppNameKube();
        String image = AppManageConfigBean.getImageName(imageBaseBean.getImage(), imageBaseBean.getImageVersion(), appManageConfigBean.getHarborUrl());
        int replicas = imageBaseBean.getReplicas();
        //String requestsMemory = imageBaseBean.getRequestsMemory();
        String requestsMemory = "100Mi";
        String limitMemory = imageBaseBean.getLimitsMemory();
        String limitCPU = imageBaseBean.getLimitsCPU();

        // 端口信息
        List<ImagePortBean> portList = imageDataBean.getImagePortList();
        // 环境变量信息
        List<ImageEnvBean> envBeanList = imageDataBean.getImageEnvList();
        // 配置文件信息
        List<ImageConfigVolumesBean> configVolumesBeanList = imageDataBean.getImageConfigVolumesList();
        // 持久化卷信息
        List<ImageStatefulSetPVCBean> statefulSetPVCList = imageDataBean.getImageStatefulSetPVCList();
        // 高可用信息
        ImageHighAvailabilityBean highAvailabilityBean = imageDataBean.getImageHA();
        // 镜像启动参数
        List<ImageArgsBean> argsBeanList = imageDataBean.getCommandArgs();

        // 1: 标签
        Map<String, String> appLabelMap = getLabelMap(AppManageConfigBean.APP_LABEL_KEY, appNameKube);


        // 2: 得到物理分组名称
        String physicalGroup = getPhysicalGroup(namespace);
        if (StringUtils.isBlank(physicalGroup))
            throw new VenusException(VenusResponseStatus.APP_DEPLOY_EXCEPTION, namespace + AppManageConfigBean.APP_DEPLOY_EXCEPTION_NOT_FOUND_PHYSICAL_GROUP);
        Map<String, String> nodeSelectorMap = getLabelMap(AppManageConfigBean.APP_LABEL_PHYSICAL_GROUP_KEY, physicalGroup);

        // 3: 拉取镜像的秘钥
        LocalObjectReference localObjectReference = k8sManageService.getLocalObjectReference(AppManageConfigBean.PULL_IMAGE_SECRET);

        // 4: 应用请求的最小内存
        Map<String, Quantity> memoryRequestsMap = getMemoryResourcesMap(requestsMemory);
        Quantity cpu_R = new QuantityBuilder()
                .withAmount("100m")
                .build();
        memoryRequestsMap.put("cpu", cpu_R);


        // 5: 应用请求的最大内存
        Map<String, Quantity> memoryLimitMap = getMemoryResourcesMap(limitMemory);
        Quantity cpu_L = new QuantityBuilder()
                .withAmount(limitCPU)
                .build();
        memoryRequestsMap.put("cpu", cpu_L);

        // 6: 端口
        List<ContainerPort> containerPortList = getContainerPortList(portList);

        // 7:卷
        List<VolumeMount> volumeMountList = new ArrayList<VolumeMount>();
        volumeMountList = getConfigVolumeMountList(configVolumesBeanList, volumeMountList);
        volumeMountList = getStatefulSetVolumeMountList(statefulSetPVCList, volumeMountList);

        // 8: 环境变量
        List<EnvVar> envVarList = getEnvVarList(envBeanList);

        // 9: 应用高可用信息
        int haType = highAvailabilityBean.getType();

        Probe haProbe = null;
        if (haType == 2) {
            // http
            haProbe = getHttpProbe(highAvailabilityBean);
        } else if (haType == 3) {
            // tcp
            haProbe = getTcpProbe(highAvailabilityBean);
        }

        // 10: 配置卷
        List<Volume> volumeList = new ArrayList<Volume>();
        volumeList = getConfigVolumeList(configVolumesBeanList, volumeList);

        // 11: 需要持久化的卷
        List<PersistentVolumeClaim> persistentVolumeClaimList = getStatefulSetVolumeList(statefulSetPVCList, appNameKube);

        // 容器
        Container container = new ContainerBuilder()
                .withName(appNameKube)
                .withImage(image)
                .withImagePullPolicy(imageBaseBean.getImagePullPolicy())
                .withEnv(envVarList)
                .withPorts(containerPortList)
                .withVolumeMounts(volumeMountList)
                .withNewResources()
                .withLimits(memoryLimitMap)
                .withRequests(memoryRequestsMap)
                .endResources()
                .build();

        // 添加高可用探针
        if (haProbe != null) {
            container.setLivenessProbe(haProbe);
            container.setReadinessProbe(haProbe);
        }


        // 容器启动命令
        int comm = imageBaseBean.getStartCommand();
        if (comm == 2) {
            String command = imageBaseBean.getCommand();
            List<String> commList = new ArrayList<String>();
            commList.add(command);
            container.setCommand(commList);
        }

        // 容器启动参数
        if (argsBeanList.size() > 0) {
            List<String> argsList = getArgsList(argsBeanList);
            container.setArgs(argsList);
        }

        // 部署
        StatefulSet statefulSet = new StatefulSetBuilder()
                .withNewMetadata()
                .withName(appNameKube)
                .withNamespace(namespace)
                .withLabels(appLabelMap)
                .endMetadata()
                .withNewSpec()
                .withServiceName(appNameKube)
                .withReplicas(replicas)
                .withNewTemplate()
                .withNewMetadata()
                .withLabels(appLabelMap)
                .endMetadata()
                .withNewSpec()
                .withNodeSelector(nodeSelectorMap)
                .withImagePullSecrets(localObjectReference)
                .withContainers(container)
                .withVolumes(volumeList)
                .endSpec()
                .endTemplate()
                .withVolumeClaimTemplates(persistentVolumeClaimList)
                .endSpec()
                .build();
        // 创建
        statefulSet = k8sManageService.createStatefulSet(statefulSet, namespace);
        if (statefulSet != null) {
            // 一个pod,一个卷
            // pvc 名称: AppManageConfigBean.STATEFULSET_PVC_VOLUME_NAME + i + appNameKube + i
            /*for (int i = 0; i < statefulSetPVCList.size(); i++) {
                ImageStatefulSetPVCBean statefulSetPVCBean = statefulSetPVCList.get(i);
                String mouthPath = statefulSetPVCBean.getMouthPath();
                String pvcName = AppManageConfigBean.STATEFULSET_PVC_VOLUME_NAME + i;
                for (int j = 0; j < replicas; j++) {
                    pvcName = pvcName + "-" + appNameKube + "-" + j;
                    k8sStorageService.setPersistentVolumeClaim(pvcName,namespace,appNameKube,mouthPath);
                }


            }*/
            return true;
        }
        return false;
    }

    @Override
    public List<Map<String, Object>> getServiceAddress(String namespace, String serviceName) throws VenusException {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            Service service = k8sManageService.getService(namespace, serviceName);
            if (service != null) {
                List<ServicePort> servicePortList = service.getSpec().getPorts();

                String serviceAddress = serviceName + "." + namespace + ":";

                for (int i = 0; i < servicePortList.size(); i++) {
                    ServicePort servicePort = servicePortList.get(i);
                    // 内部端口
                    int in_port = servicePort.getPort().intValue();
                    int out_port = 0;
                    try {
                        // 外部端口
                        out_port = servicePort.getNodePort().intValue();
                    } catch (NullPointerException n) {
                        out_port = 0;
                    }

                    String msg = "内部: " + serviceAddress + in_port;

                    if (out_port > 0) {
                        msg = msg + "     外部: " + serviceAddress + out_port;
                    }
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("id", i);
                    map.put("name", msg);
                    list.add(map);
                }
            }
        } catch (Exception e) {
            return list;
        }

        return list;
    }

    /*
    * 删除ingress
    * */
    @Override
    public boolean deleteIngress(String namespace, String appNameKube) throws VenusException {
        Map<String, String> appMap = getLabelMap(AppManageConfigBean.APP_LABEL_KEY, appNameKube);
        boolean flag = k8sManageService.deleteIngressByLabels(appMap, namespace);
        return flag;
    }

    /*
    * 删除ingress
    * */
    @Override
    public boolean deleteIngressByName(String ingressName, String namespace) throws VenusException {
        return k8sManageService.deleteIngressByName(ingressName, namespace);
    }

    /*
    * 删除hpa
    * */
    @Override
    public boolean deleteHPAByLabels(String namespace, String appNameKube) throws VenusException {
        Map<String, String> appMap = getLabelMap(AppManageConfigBean.APP_LABEL_KEY, appNameKube);
        return k8sManageService.deleteHPAByLabels(appMap, namespace);
    }

    /*
    * 获得服务列表,根据标签
    * */
    @Override
    public List<Map<String, Object>> getServiceAddressByLabels(String namespace, String appNameKube) throws VenusException {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, String> appMap = getLabelMap(AppManageConfigBean.APP_LABEL_KEY, appNameKube);
        try {
            ServiceList serviceList = k8sManageService.getServiceListByLabels(appMap, namespace);
            if (serviceList != null) {

                List<Service> serviceListItems = serviceList.getItems();
                for (int i = 0; i < serviceListItems.size(); i++) {
                    Service service1 = serviceListItems.get(i);
                    // 服务名称
                    String serviceName = service1.getMetadata().getName();
                    String serviceAddress = serviceName + "." + namespace + ":";

                    // 得到服务类型注解
                    String serviceType = "";
                    Map<String, String> annotationsMap = service1.getMetadata().getAnnotations();
                    if (annotationsMap != null && annotationsMap.size() > 0) {
                        serviceType = annotationsMap.get(AppManageConfigBean.SERVICE_TYPE);
                    }

                    List<ServicePort> servicePortList = service1.getSpec().getPorts();
                    if (serviceName.endsWith("-in") || AppManageConfigBean.SERVICE_TYPE_IN.equals(serviceType)) {
                        // 内部服务
                        for (int j = 0; j < servicePortList.size(); j++) {
                            ServicePort servicePort = servicePortList.get(j);
                            // 内部端口
                            int in_port = servicePort.getPort().intValue();
                            String msg = "内部: " + serviceAddress + in_port;
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("id", i);
                            map.put("name", msg);
                            list.add(map);
                        }
                    } else if (serviceName.endsWith("-tcp") || AppManageConfigBean.SERVICE_TYPE_TCP.equals(serviceType)) {
                        // tcp 外部服务
                        ServicePort servicePort = servicePortList.get(0);
                        int in_port = servicePort.getPort().intValue();
                        int out_port = 0;
                        try {
                            // 外部端口
                            out_port = servicePort.getNodePort().intValue();
                        } catch (NullPointerException n) {
                            out_port = 0;
                        }

                        String msg = "内部(TCP): " + serviceAddress + in_port;

                        if (out_port > 0) {
                            msg = msg + "     外部(TCP): " + serviceAddress + out_port;
                        }
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", i);
                        map.put("name", msg);
                        list.add(map);
                    } else if (serviceName.endsWith("-http") || AppManageConfigBean.SERVICE_TYPE_HTTP.equals(serviceType)) {
                        // http 外部服务
                        ServicePort httpServicePort = servicePortList.get(0);
                        int http_port = httpServicePort.getPort().intValue();

                        String msg = "内部(HTTP): " + serviceAddress + http_port;

                        // 获得域名
                        String domainName = getDomainName(namespace, appNameKube, serviceName, http_port);
                        if (StringUtils.isNotBlank(domainName)) {
                            msg = msg + "     外部(HTTP): " + domainName;
                        }
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", i);
                        map.put("name", msg);
                        list.add(map);
                    }
                }
            }
        } catch (Exception e) {
            return list;
        }

        return list;
    }

    @Override
    public int addDomainName(String namespace, String appNameKube, String serviceName, String ingressName, String domainName, int port) throws VenusException {
        String sql = "INSERT INTO t_app_domain_name(id,port,name,ingress_name,app_name_kube,service_name,namespace,create_time,last_update_time) " +
                "VALUES(?,?,?,?,?,?,?,NOW(),NOW())";
        List<Object> list = new ArrayList<Object>();
        list.add(StringUtil.getUUID());
        list.add(port);
        list.add(domainName);
        list.add(ingressName);
        list.add(appNameKube);
        list.add(serviceName);
        list.add(namespace);
        int code = jdbcTemplate.update(sql, list.toArray());
        return code;
    }

    /*
   * http服务,获得域名服务
   * */
    @Override
    public String getDomainName(String namespace, String appNameKube, String serviceName, int port) throws VenusException {
        String sql = "SELECT name FROM t_app_domain_name WHERE port=? AND app_name_kube=? AND service_name = ? AND namespace= ?";
        List<Object> list = new ArrayList<Object>();
        list.add(port);
        list.add(appNameKube);
        list.add(serviceName);
        list.add(namespace);
        String domainName = "";
        try {
            Map<String, Object> map = jdbcTemplate.queryForMap(sql, list.toArray());
            if (map.size() > 0) {
                domainName = (String) map.get("name");
            }
        } catch (EmptyResultDataAccessException e) {
            return domainName;
        }
        return domainName;
    }

    @Override
    public Map<String, Object> getDomainNameBean(String namespace, String appNameKube, String serviceName, int port) throws VenusException {
        String sql = "SELECT *  FROM t_app_domain_name WHERE port=? AND app_name_kube=? AND service_name = ? AND namespace= ?";
        List<Object> list = new ArrayList<Object>();
        list.add(port);
        list.add(appNameKube);
        list.add(serviceName);
        list.add(namespace);
        Map<String, Object> domainName = new HashMap<>();
        try {
            domainName = jdbcTemplate.queryForMap(sql, list.toArray());
        } catch (EmptyResultDataAccessException e) {
            return domainName;
        }
        return domainName;
    }

    @Override
    public Map<String, Object> getDomainName(String namespace, String serviceName) throws VenusException {
        String sql = "SELECT * FROM t_app_domain_name WHERE  service_name = ? AND namespace= ?";
        List<Object> list = new ArrayList<Object>();
        list.add(serviceName);
        list.add(namespace);
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map = jdbcTemplate.queryForMap(sql, list.toArray());

        } catch (EmptyResultDataAccessException e) {
            return map;
        }
        return map;
    }

    @Override
    public int deleteDomainName(String namespace, String appNameKube) throws VenusException {
        String sql = "DELETE FROM t_app_domain_name WHERE namespace = ? AND app_name_kube = ?";
        List<Object> list = new ArrayList<Object>();
        list.add(namespace);
        list.add(appNameKube);
        int code = jdbcTemplate.update(sql, list.toArray());
        return code;
    }

    @Override
    public int deleteDomainNameById(String id) throws VenusException {
        String sql = "DELETE FROM t_app_domain_name WHERE id = ?";
        List<Object> list = new ArrayList<Object>();
        list.add(id);
        int code = jdbcTemplate.update(sql, list.toArray());
        return code;
    }

    /*
    * 校验http服务域名
    * */
    @Override
    public boolean validateDomainName(String domainName) throws VenusException {
        String sql = "SELECT id FROM t_app_domain_name WHERE name=? ";
        List<Object> list = new ArrayList<Object>();
        list.add(domainName);
        try {
            Map<String, Object> map = jdbcTemplate.queryForMap(sql, list.toArray());
            if (map.size() > 0) {
                return true;
            }
        } catch (EmptyResultDataAccessException e) {
            return false;
        }
        return true;
    }

    /*
    * 获得应用的服务配置
    * */
    @Override
    public List<Map<String, Object>> getDeploymentConfigMap(String namespace, String appNameKube) throws VenusException {
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        Deployment deployment = k8sManageService.getDeployment(namespace, appNameKube);
        if (deployment == null)
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用不存在");
        // 判断是否存在配置组
        List<Volume> volumeList = deployment.getSpec().getTemplate().getSpec().getVolumes();
        if (volumeList == null || volumeList.size() == 0) {
            return mapList;
        }

        // 获取配置目录
        Map<String, String> volumeMountMap_str = new HashMap<String, String>();
        List<Container> containerList = deployment.getSpec().getTemplate().getSpec().getContainers();
        for (Container container : containerList) {
            List<VolumeMount> volumeMountList = container.getVolumeMounts();
            if (volumeMountList == null) continue;
            if (volumeMountList.size() == 0) continue;
            for (VolumeMount volumeMount : volumeMountList) {
                String volumeMountPath = volumeMount.getMountPath();
                String volumeMountName = volumeMount.getName();
                if (StringUtils.isNotBlank(volumeMountPath)) {
                    volumeMountMap_str.put(volumeMountName, volumeMountPath);
                }
            }

        }

        if (volumeMountMap_str.size() > 0) {
            for (int i = 0; i < volumeList.size(); i++) {
                Volume volume = volumeList.get(i);
                // 卷名称
                String volumeName = volume.getName();
                // 配置组
                ConfigMapVolumeSource configMapVolumeSource = volume.getConfigMap();

                if (configMapVolumeSource != null) {
                    // 配置组名
                    String configGroup = configMapVolumeSource.getName();
                    Map<String, Object> map = new HashMap<String, Object>();
                    List<String> configFilesList = new ArrayList<String>();
                    // 遍历配置组
                    List<KeyToPath> keyToPathList = configMapVolumeSource.getItems();
                    StringBuilder stringBuilder = new StringBuilder();
                    // 配置文件
                    int keyToPathListSize = keyToPathList.size();
                    for (int j = 0; j < keyToPathListSize; j++) {
                        KeyToPath keyToPath = keyToPathList.get(j);

                        configFilesList.add(keyToPath.getKey());

                        stringBuilder.append(keyToPath.getKey());
                        if (j < keyToPathListSize - 1) {
                            stringBuilder.append(",");
                        }
                    }
                    // 添加
                    map.put("id", StringUtil.getUUID());
                    map.put("configFiles", configFilesList);
                    map.put("volumeName", volumeName);
                    map.put("configGroup", configGroup);
                    map.put("configFilesStr", stringBuilder.toString());

                    // 获得配置目录
                    map.put("mouthPath", volumeMountMap_str.get(volumeName));

                    // 添加
                    mapList.add(map);
                }
            }
        }
        return mapList;
    }


    /*
    * 修改服务配置
    * */
    @Override
    public boolean editDeploymentConfigMapToApp(AppConfigMapManageBean appConfigMapManageBean) throws VenusException {
        String namespace = appConfigMapManageBean.getNamespace();
        String appNameKube = appConfigMapManageBean.getAppNameKube();
        String volumeName = appConfigMapManageBean.getVolumeName();
        String configGroup = appConfigMapManageBean.getConfigGroup();
        String[] configFiles = appConfigMapManageBean.getConfigFiles();

        // 得到应用
        Deployment deployment = k8sManageService.getDeployment(namespace, appNameKube);
        if (deployment == null) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用不存在");
        }

        // 获得卷
        List<Volume> volumeList = deployment.getSpec().getTemplate().getSpec().getVolumes();
        List<Volume> newVolumeList = new ArrayList<Volume>();

        for (Volume volume : volumeList) {
            if (volume.getName().equals(volumeName)) {
                ConfigMapVolumeSource configMapVolumeSource = volume.getConfigMap();
                configMapVolumeSource.setName(configGroup);
                List<KeyToPath> keyToPathList = getKeyToPathList(configFiles);
                configMapVolumeSource.setItems(keyToPathList);
            }
            newVolumeList.add(volume);
        }

        // 重新设置卷
        deployment.getSpec().getTemplate().getSpec().setVolumes(newVolumeList);

        // 重新创建应用
        Deployment deployment1 = k8sManageService.createOrReplaceDeployment(deployment, namespace);

        if (deployment1 != null) {
            return true;
        }
        return false;
    }

    /*
    * 新增应用的服务配置
    * */
    @Override
    public boolean addDeploymentConfigMapToApp(AppConfigMapManageBean appConfigMapManageBean) throws VenusException {
        String namespace = appConfigMapManageBean.getNamespace();
        String appNameKube = appConfigMapManageBean.getAppNameKube();
        String volumeName = appConfigMapManageBean.getVolumeName();
        String configGroup = appConfigMapManageBean.getConfigGroup();
        String[] configFiles = appConfigMapManageBean.getConfigFiles();
        String mouthPath = appConfigMapManageBean.getMouthPath();
        // 先得到应用
        Deployment deployment = k8sManageService.getDeployment(namespace, appNameKube);

        if (deployment == null) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用不存在");
        }

        // 获得卷
        List<Volume> volumeList = deployment.getSpec().getTemplate().getSpec().getVolumes();
        int index = volumeList.size() + 1;

        String volumeMouthName = AppManageConfigBean.CONFIGMAP_VOLUME_NAME + index;

        // 新建volumeMouth
        VolumeMount volumeMount = getVolumeMount(volumeMouthName, mouthPath);

        // 新建volume
        List<KeyToPath> keyToPathList = getKeyToPathList(configFiles);
        Volume volume = new VolumeBuilder()
                .withName(volumeMouthName) // 卷名
                .withNewConfigMap() // 配置组名称
                .withName(configGroup)
                .withItems(keyToPathList)
                .endConfigMap()
                .build();

        volumeList.add(volume);

        // 设置
        List<Container> containerList = deployment.getSpec().getTemplate().getSpec().getContainers();
        for (Container container : containerList) {
            container.getVolumeMounts().add(volumeMount);
        }

        deployment.getSpec().getTemplate().getSpec().setVolumes(volumeList);

        Deployment deployment1 = k8sManageService.createOrReplaceDeployment(deployment, namespace);

        if (deployment1 != null) {
            return true;
        }
        return false;
    }

    /*
    * 删除服务配置
    * */
    @Override
    public boolean deleteDeploymentConfigMapToApp(AppConfigMapManageBean appConfigMapManageBean) throws VenusException {

        String namespace = appConfigMapManageBean.getNamespace();
        String appNameKube = appConfigMapManageBean.getAppNameKube();
        String volumeName = appConfigMapManageBean.getVolumeName();
        String configGroup = appConfigMapManageBean.getConfigGroup();
        String[] configFiles = appConfigMapManageBean.getConfigFiles();

        // 得到应用
        Deployment deployment = k8sManageService.getDeployment(namespace, appNameKube);
        if (deployment == null) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用不存在");
        }

        // 获得卷
        List<Volume> volumeList = deployment.getSpec().getTemplate().getSpec().getVolumes();
        List<Volume> newVolumeList = new ArrayList<Volume>();

        for (Volume volume : volumeList) {
            if (!volume.getName().equals(volumeName)) {
                newVolumeList.add(volume);
            }
        }


        List<Container> containerList = deployment.getSpec().getTemplate().getSpec().getContainers();
        for (Container container : containerList) {
            List<VolumeMount> volumeMountList = container.getVolumeMounts();
            List<VolumeMount> newVolumeMountList = new ArrayList<VolumeMount>();
            for (VolumeMount volumeMount : volumeMountList) {
                if (!volumeMount.getName().equals(volumeName)) {
                    newVolumeMountList.add(volumeMount);
                }
            }
            container.setVolumeMounts(newVolumeMountList);
        }

        // 重新设置
        deployment.getSpec().getTemplate().getSpec().setVolumes(newVolumeList);
        deployment.getSpec().getTemplate().getSpec().setContainers(containerList);

        Deployment deployment1 = k8sManageService.createOrReplaceDeployment(deployment, namespace);

        if (deployment1 != null) {
            return true;
        }
        return false;
    }

    /*
    * 获取自动伸缩的数据
    * */
    @Override
    public List<Map<String, Object>> getHPAData(String hpaName, String namespace) throws VenusException {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        HorizontalPodAutoscaler horizontalPodAutoscaler = k8sManageService.getHorizontalPodAutoscaler(namespace, hpaName);
        if (horizontalPodAutoscaler != null) {
            HorizontalPodAutoscalerStatus status = horizontalPodAutoscaler.getStatus();


            // 目标CPU使用率
            int targetCPUUtilizationPercentage = horizontalPodAutoscaler.getSpec().getTargetCPUUtilizationPercentage().intValue();

            int currentCPUUtilizationPercentage = 0;
            try {
                // 当前CPU使用率
                currentCPUUtilizationPercentage = status.getCurrentCPUUtilizationPercentage().intValue();
            } catch (Exception e) {
                currentCPUUtilizationPercentage = 0;
            }

            // 当前实例数
            int currentReplicas = 0;

            try {
                currentReplicas = status.getCurrentReplicas().intValue();
            } catch (Exception e) {
                currentReplicas = 0;
            }

            // 最小实例数
            int minReplicas = horizontalPodAutoscaler.getSpec().getMinReplicas().intValue();

            // 最大实例数
            int maxReplicas = horizontalPodAutoscaler.getSpec().getMaxReplicas().intValue();

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("currentCPUUtilizationPercentage", currentCPUUtilizationPercentage);
            map.put("targetCPUUtilizationPercentage", targetCPUUtilizationPercentage);
            map.put("currentReplicas", currentReplicas);
            map.put("minReplicas", minReplicas);
            map.put("maxReplicas", maxReplicas);
            map.put("appNameKube", hpaName.replace("-hpa", ""));
            list.add(map);


        }
        return list;
    }

    /*
    * 展示应用服务配置
    * */
    @Override
    public List<ImagePortBean> getAppService(String namespace, String appNameKube) throws VenusException {
        List<ImagePortBean> imagePortBeanList = new ArrayList<ImagePortBean>();
        Map<String, String> appMap = getLabelMap(AppManageConfigBean.APP_LABEL_KEY, appNameKube);
        try {
            ServiceList serviceList = k8sManageService.getServiceListByLabels(appMap, namespace);
            if (serviceList != null) {

                List<Service> serviceListItems = serviceList.getItems();
                for (int i = 0; i < serviceListItems.size(); i++) {
                    ImagePortBean imagePortBean = null;
                    Service service1 = serviceListItems.get(i);
                    // 服务名称
                    String serviceName = service1.getMetadata().getName();

                    // 得到服务类型注解
                    String serviceType = "";
                    Map<String, String> annotationsMap = service1.getMetadata().getAnnotations();
                    if (annotationsMap != null && annotationsMap.size() > 0) {
                        serviceType = annotationsMap.get(AppManageConfigBean.SERVICE_TYPE);
                    }

                    String createTime = service1.getMetadata().getCreationTimestamp().replaceAll("T", " ").replaceAll("Z", "");
                    createTime = DateUtil.calculate(DateUtil.yyyy_MM_dd_HH_mm_ss, createTime, 28800000);
                    String serviceAddress = serviceName + "." + namespace + ":";
                    List<ServicePort> servicePortList = service1.getSpec().getPorts();
                    if (serviceName.endsWith("-in") || AppManageConfigBean.SERVICE_TYPE_IN.equals(serviceType)) {

                        // 内部服务
                        for (int j = 0; j < servicePortList.size(); j++) {
                            ImagePortBean portBean = new ImagePortBean();


                            ServicePort servicePort = servicePortList.get(j);
                            // 内部端口
                            int in_port = servicePort.getPort().intValue();

                            portBean.setId(StringUtil.getUUID());
                            portBean.setServiceName(serviceName);
                            portBean.setPort(in_port);
                            portBean.setProtocol("TCP");
                            portBean.setVisible(false);
                            //portBean.setPortType("dynamic");
                            portBean.setNodePort(0);
                            //portBean.setDomainNameType("dynamic");
                            portBean.setDomainName("");
                            portBean.setNamespace(namespace);
                            portBean.setCreateTime(createTime);

                            imagePortBeanList.add(portBean);

                        }
                    } else if (serviceName.endsWith("-tcp") || AppManageConfigBean.SERVICE_TYPE_TCP.equals(serviceType)) {
                        imagePortBean = new ImagePortBean();
                        // tcp 外部服务
                        ServicePort servicePort = servicePortList.get(0);
                        int in_port = servicePort.getPort().intValue();
                        int out_port = 0;
                        try {
                            // 外部端口
                            out_port = servicePort.getNodePort().intValue();
                        } catch (NullPointerException n) {
                            out_port = 0;
                        }

                        imagePortBean.setId(StringUtil.getUUID());
                        imagePortBean.setServiceName(serviceName);
                        imagePortBean.setPort(in_port);
                        imagePortBean.setProtocol("TCP");
                        imagePortBean.setVisible(true);
                        imagePortBean.setNodePort(out_port);
                        imagePortBean.setDomainName("");
                        imagePortBean.setNamespace(namespace);
                        imagePortBean.setCreateTime(createTime);

                    } else if (serviceName.endsWith("-http") || AppManageConfigBean.SERVICE_TYPE_HTTP.equals(serviceType)) {
                        imagePortBean = new ImagePortBean();
                        // http 外部服务
                        ServicePort httpServicePort = servicePortList.get(0);
                        int http_port = httpServicePort.getPort().intValue();

                        //String msg = "内部(HTTP): " + serviceAddress + http_port;

                        // 获得域名
                        //String domainName = getDomainName(namespace, appNameKube, serviceName, http_port);
                        Map<String, Object> domainNameMap = getDomainNameBean(namespace, appNameKube, serviceName, http_port);
                        String domainName = "", ingressName = "";
                        if (domainNameMap.size() > 0) {
                            domainName = (String) domainNameMap.get("name");
                            ingressName = (String) domainNameMap.get("ingress_name");
                        }

//                        if (StringUtils.isNotBlank(domainName)) {
//                            msg = msg + "     外部(HTTP): " + domainName;
//                        }

                        imagePortBean.setId(StringUtil.getUUID());
                        imagePortBean.setServiceName(serviceName);
                        imagePortBean.setPort(http_port);
                        imagePortBean.setVisible(true);
                        imagePortBean.setProtocol("HTTP");
                        imagePortBean.setNodePort(0);
                        imagePortBean.setDomainName(domainName);
                        imagePortBean.setIngressName(ingressName);
                        imagePortBean.setNamespace(namespace);
                        imagePortBean.setCreateTime(createTime);

                    }

                    // 添加
                    if (imagePortBean != null) {
                        imagePortBeanList.add(imagePortBean);
                    }
                }
            }
        } catch (Exception e) {
            return imagePortBeanList;
        }

        return imagePortBeanList;
    }

    /*
    * 展示应用服务信息
    * */
    @Override
    public List<ServiceBean> getAppServiceByNamespace(String namespace) throws VenusException{
        List<ServiceBean> serviceBeans = new ArrayList<ServiceBean>();
        ServiceList serviceList =k8sManageService.getServiceListByNamespace(namespace);
        if (serviceList != null) {
            List<Service> serviceListItems = serviceList.getItems();
            ServiceBean serviceBean=null;
            for(Service service:serviceListItems){
                serviceBean=new ServiceBean();
                serviceBean.setUid(service.getMetadata().getUid());
                serviceBean.setName(service.getMetadata().getName());
                serviceBean.setNamespace(service.getMetadata().getNamespace());
                // 获取创建时间
                String createTime = service.getMetadata().getCreationTimestamp().replaceAll("T", " ").replaceAll("Z", "");
                createTime = DateUtil.calculate(DateUtil.yyyy_MM_dd_HH_mm_ss, createTime, 28800000 - 240000);
                String timeDiff = DateUtil.getTimeDifference(DateUtil.yyyy_MM_dd_HH_mm_ss, createTime, DateUtil.getCurrentTime(DateUtil.yyyy_MM_dd_HH_mm_ss));
                serviceBean.setCreationTimestamp(timeDiff);
                serviceBean.setSessionAffinity(service.getSpec().getSessionAffinity());
                serviceBean.setType(service.getSpec().getType());
                serviceBean.setClusterIP(service.getSpec().getClusterIP());
                serviceBean.setLabels(service.getMetadata().getLabels());
                serviceBean.setAnnotations(service.getMetadata().getAnnotations());
                serviceBean.setSelectors(service.getSpec().getSelector());
                serviceBean.setStatus(service.getStatus());
                List<ServicePortBean> servicePortBeans=new ArrayList<>();
                List<ServicePort> servicePorts=service.getSpec().getPorts();
                ServicePortBean servicePortBean=null;
                for(ServicePort servicePort:servicePorts){
                    servicePortBean=new ServicePortBean();
                    servicePortBean.setName(servicePort.getName());
                    if(servicePort.getNodePort()!=null){
                        servicePortBean.setNodePort(servicePort.getNodePort());
                    }
                    servicePortBean.setPort(servicePort.getPort());
                    servicePortBean.setProtocal(servicePort.getProtocol());
                    servicePortBean.setTargetPort(servicePort.getTargetPort().getIntVal());
                    servicePortBeans.add(servicePortBean);
                }
                serviceBean.setServicePorts(servicePortBeans);
                serviceBeans.add(serviceBean);
            }
        }
        return serviceBeans;
    }

    /*
    * 获得deployment应用的端口
    * */
    @Override
    public List<Integer> getDeploymentPorts(String namespace, String appNameKube) throws VenusException {
        List<Integer> list = new ArrayList<Integer>();
        Deployment deployment = k8sManageService.getDeployment(namespace, appNameKube);
        if (deployment != null) {
            List<Container> containerList = deployment.getSpec().getTemplate().getSpec().getContainers();
            containerList.forEach(container -> {
                List<ContainerPort> containerPortList = container.getPorts();
                containerPortList.forEach(containerPort -> {
                    list.add(containerPort.getContainerPort());
                });

            });
        }
        return list;
    }

    /*
    * 获得statefulSet 应用端口
    * */
    @Override
    public List<Integer> getStatefulSetPorts(String namespace, String appNameKube) throws VenusException {
        List<Integer> list = new ArrayList<Integer>();
        StatefulSet statefulSet = k8sManageService.getStatefulSet(namespace, appNameKube);
        if (statefulSet != null) {
            List<Container> containerList = statefulSet.getSpec().getTemplate().getSpec().getContainers();
            containerList.forEach(container -> {
                List<ContainerPort> containerPortList = container.getPorts();
                containerPortList.forEach(containerPort -> {
                    list.add(containerPort.getContainerPort());
                });

            });
        }
        return list;
    }

    @Override
    public boolean validateServiceName(String serviceName, String namespace) throws VenusException {
        Service service = k8sManageService.getService(namespace, serviceName);
        if (service != null) {
            return true;
        }
        return false;
    }

    /*
      * 修改应用服务的服务端口,nodePort,k8s集群节点物理主机
      * */
    @Override
    public boolean editAppServiceNodePort(ImagePortBean imagePortBean) throws VenusException {
        // 得到service
        Service service = k8sManageService.getService(imagePortBean.getNamespace(),imagePortBean.getServiceName());

        if (service != null) {
            int size = service.getSpec().getPorts().size();

            if (size == 1) {
                service.getSpec().getPorts().get(0).setNodePort(imagePortBean.getNodePort());

                // 更新
                Service service1 = k8sManageService.createOrUpdateService(imagePortBean.getNamespace(),service);
                if (service1 != null) {
                    return true;
                }
            }
        }
        return false;
    }

    /*
    *修改应用服务的服务域名
    * */
    @Override
    public boolean editAppServiceDomainName(ImagePortBean imagePortBean) throws VenusException {
        // 得到ingress
        Ingress ingress = k8sManageService.getIngress(imagePortBean.getNamespace(),imagePortBean.getIngressName());
        if (ingress != null) {
            int size = ingress.getSpec().getRules().size();
            if (size ==1) {
                ingress.getSpec().getRules().get(0).setHost(imagePortBean.getDomainName());
                Ingress ingress1 = k8sManageService.createOrUpdateIngress(imagePortBean.getNamespace(),ingress);
                if (ingress1 != null) {
                    // 修改数据域名
                    String sql = "UPDATE t_app_domain_name t SET t.name = ? WHERE t.ingress_name = ? AND t.namespace = ? ";
                    List<Object> list = new ArrayList<Object>();
                    list.add(imagePortBean.getDomainName());
                    list.add(imagePortBean.getIngressName());
                    list.add(imagePortBean.getNamespace());
                    int row = jdbcTemplate.update(sql,list.toArray());

                    return row > 0 ? true : false;
                }
            }
        }
        return false;
    }

    /*
    * 得到tcp服务端口列表,根据空间名称
    * */
    @Override
    public List<Integer> getServicePortList() throws VenusException {
        List<Integer> integerList = new ArrayList<Integer>();
        ServiceList list = k8sManageService.getServiceList();
        if (list != null) {
            List<Service> serviceList = list.getItems();
            // 遍历
            serviceList.forEach(service -> {
                // 得到服务类型
                String serviceType = service.getSpec().getType();
                if ("NodePort".equals(serviceType)) {
                    List<ServicePort> servicePortList = service.getSpec().getPorts();
                    servicePortList.forEach(servicePort -> {
                        integerList.add(servicePort.getNodePort());
                    });
                }
            });
        }
        return integerList;
    }


    /*
    * 展示ingress信息
    * */
     @Override
     public List<IngressBean> getIngressByNamespace(String namespace) throws VenusException{
        IngressList ingressList=k8sManageService.getIngressList(namespace);
        List<IngressBean> ingressBeans=new ArrayList<>();
         if(ingressList!=null){
             List<Ingress> ingresses=ingressList.getItems();
             IngressBean ingressBean=null;
             for(Ingress ingress:ingresses){
                 ingressBean=new IngressBean();
                 ingressBean.setName(ingress.getMetadata().getName());
                 String createTime = ingress.getMetadata().getCreationTimestamp().replaceAll("T", " ").replaceAll("Z", "");
                 createTime = DateUtil.calculate(DateUtil.yyyy_MM_dd_HH_mm_ss, createTime, 28800000 - 240000);
                 String timeDiff = DateUtil.getTimeDifference(DateUtil.yyyy_MM_dd_HH_mm_ss, createTime, DateUtil.getCurrentTime(DateUtil.yyyy_MM_dd_HH_mm_ss));
                 ingressBean.setCreationTimestamp(timeDiff);
                 ingressBean.setNamespace(ingress.getMetadata().getNamespace());
                 List<IngressRule> ingressRules=ingress.getSpec().getRules();
                 List<IngressRuleBean> ingressRuleBeans=new ArrayList<>();
                 IngressRuleBean ingressRuleBean=null;
                 Object ingressDesc=ingress.getMetadata().getAnnotations().get("ingressDesc");
                 ingressBean.setIngressDesc(ingressDesc==null?"":ingressDesc.toString());
                 for(IngressRule ingressRule:ingressRules){
                     ingressRuleBean=new IngressRuleBean();
                     ingressRuleBean.setHost(ingressRule.getHost());
                     List<HTTPIngressPath> httpIngressPaths=ingressRule.getHttp().getPaths();
                     List<IngressHttpPathBean> ingressHttpPathBeans=new ArrayList<>();
                     IngressHttpPathBean ingressHttpPathBean=null;
                     for(HTTPIngressPath httpIngressPath:httpIngressPaths){
                         ingressHttpPathBean=new IngressHttpPathBean();
                         ingressHttpPathBean.setPath(httpIngressPath.getPath());
                         Map<String,Object> map=new HashMap<>();
                         map.put("serviceName",httpIngressPath.getBackend().getServiceName());
                         map.put("servicePort",httpIngressPath.getBackend().getServicePort().getIntVal());

                         ingressHttpPathBean.setBackend(map);
                         ingressHttpPathBeans.add(ingressHttpPathBean);
                     }
                     ingressRuleBean.setIngressHttpPaths(ingressHttpPathBeans);
                     ingressRuleBeans.add(ingressRuleBean);
                 }
                 ingressBean.setIngressRules(ingressRuleBeans);
                 ingressBeans.add(ingressBean);
             }
         }
        return ingressBeans;
    }


    /**
     * 新增或者修改ingress
     * @param  ingressBean
     * @return
     * @throws VenusException
     */
    @Override
    public boolean saveOrUpdateIngress(IngressBean ingressBean) throws VenusException{
        String ingressDesc=ingressBean.getIngressDesc();
        Map<String,String> annoMap = new HashMap<String,String>();
        annoMap.put("kubernetes.io/ingress.class","traefik");
        if(StringUtil.isEmpty(ingressDesc)){
            annoMap.put("ingressDesc","");
        }else{
            annoMap.put("ingressDesc",ingressDesc);
        }

        List<IngressRule> ingressRules=new ArrayList<>();
        for(IngressRuleBean ingressRuleBean:ingressBean.getIngressRules()){
            // 规则
            List<HTTPIngressPath> httpIngressPaths=new ArrayList<>();
            for(IngressHttpPathBean ingressHttpPathBean:ingressRuleBean.getIngressHttpPaths()){
                HTTPIngressPath httpIngressPath = new HTTPIngressPathBuilder()
                        .withPath(ingressHttpPathBean.getPath())
                        .withNewBackend()
                        .withServiceName(ingressHttpPathBean.getBackend().get("serviceName").toString())
                        .withNewServicePort()
                        .withIntVal((Integer) ingressHttpPathBean.getBackend().get("servicePort"))
                        .endServicePort()
                        .endBackend()
                        .build();
                httpIngressPaths.add(httpIngressPath);
            }
            HTTPIngressPath[] httpIngressPathsArr=new HTTPIngressPath[httpIngressPaths.size()];
            httpIngressPaths.toArray(httpIngressPathsArr);
            IngressRule ingressRule = new IngressRuleBuilder()
                    .withHost(ingressRuleBean.getHost())
                    .withNewHttp()
                    .withPaths(httpIngressPathsArr)
                    .endHttp()
                    .build();
            ingressRules.add(ingressRule);
        }
        IngressRule[] ingressRulesArr=new IngressRule[ingressRules.size()];
        ingressRules.toArray(ingressRulesArr);

        Ingress ingress = new IngressBuilder()
                .withNewMetadata()
                .withName(ingressBean.getName())
                .withNamespace(ingressBean.getNamespace())
                .withAnnotations(annoMap)
                .endMetadata()
                .withNewSpec()
                .withRules(ingressRulesArr)
                .endSpec()
                .build();
        ingress=k8sManageService.createOrUpdateIngress(ingressBean.getNamespace(),ingress);
        if(ingress!=null){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 根据空间和ingress名称获取ingress对象
     * @param namespace
     * @param ingressName
     * @return
     * @throws VenusException
     */
    public Ingress getIngress(String namespace,String ingressName)throws VenusException{
        return k8sManageService.getIngress(namespace,ingressName);
    }

    /*
    * add by 业哥 180511
    * 根据应用类型,获得应用实例数
    * @param appKind 应用类型
    * @param namespace 空间名称
    * @param appNameKube 应用名称
    * @param appManageBean 应用管理bean
    * */
    public void getAppBaseInfo(String appKind, String namespace, String appNameKube,AppManageBean appManageBean) throws VenusException{
        Container container = null;
        if (AppManageConfigBean.Kind_Deployment.indexOf(appKind) != -1) {
            Deployment deployment = k8sManageService.getDeployment(namespace, appNameKube);
            container=deployment.getSpec().getTemplate().getSpec().getContainers().get(0);
        } else if (AppManageConfigBean.Kind_StatefulSet.indexOf(appKind) != -1) {
            StatefulSet statefulSet = k8sManageService.getStatefulSet(namespace, appNameKube);
            container=statefulSet.getSpec().getTemplate().getSpec().getContainers().get(0);
        } else if (AppManageConfigBean.Kind_DaemonSet.indexOf(appKind) != -1) {

        }
        if(container!=null){
            appManageBean.setCommand(container.getCommand());

            appManageBean.setArgs(container.getArgs());
            appManageBean.setEnvs(container.getEnv());
            if(container.getResources()!=null){
                Map<String,String> limits=new HashMap<>();
                if(container.getResources().getLimits()!=null){
                    limits.put("cpu",container.getResources().getLimits().get("cpu").getAmount());
                    limits.put("memory",container.getResources().getLimits().get("memory").getAmount());
                }else{
                    limits.put("cpu","");
                    limits.put("memory","");
                }
                appManageBean.setLimits(limits);

                Map<String,String> requests=new HashMap<>();
                if(container.getResources().getRequests()!=null){
                    requests.put("cpu",container.getResources().getRequests().get("cpu").getAmount());
                    requests.put("memory",container.getResources().getRequests().get("memory").getAmount());
                }else{
                    requests.put("cpu","");
                    requests.put("memory","");
                }
                appManageBean.setRequests(requests);
            }
        }
    }

    /*
    * add by 业哥 180515
    * 根据应用类型,设置应用相关信息(含资源,启动参数,环境变量)
    * */
    public boolean setAppBaseInfo(AppBaseInfoBean appBaseInfoBean) throws VenusException{
        List<Container> containers = null;
        Deployment deployment=null;
        StatefulSet statefulSet=null;
        if (AppManageConfigBean.Kind_Deployment.indexOf(appBaseInfoBean.getAppKind()) != -1) {
            deployment = k8sManageService.getDeployment(appBaseInfoBean.getNamespace(), appBaseInfoBean.getAppNameKube());
            containers=deployment.getSpec().getTemplate().getSpec().getContainers();
            Deployment deployment1 = k8sManageService.getK8sClient().apps().deployments().inNamespace(appBaseInfoBean.getNamespace()).withName(appBaseInfoBean.getAppNameKube()).createOrReplace(deployment);
        } else if (AppManageConfigBean.Kind_StatefulSet.indexOf(appBaseInfoBean.getAppKind()) != -1) {
            statefulSet = k8sManageService.getStatefulSet(appBaseInfoBean.getNamespace(), appBaseInfoBean.getAppNameKube());
            containers=statefulSet.getSpec().getTemplate().getSpec().getContainers();
            StatefulSet statefulSet1 = k8sManageService.getK8sClient().apps().statefulSets().inNamespace(appBaseInfoBean.getNamespace()).withName(appBaseInfoBean.getAppNameKube()).createOrReplace(statefulSet);
        } else if (AppManageConfigBean.Kind_DaemonSet.indexOf(appBaseInfoBean.getAppKind()) != -1) {

        }
        //修改参数  0:资源配置,1:启动参数,2:环境变量
            for(Container container:containers){
                if(appBaseInfoBean.getUpdateType()==0){
                    Map<String, Quantity> requestsMap = new HashMap<String, Quantity>();
                    Map<String, Quantity> limitsMap = new HashMap<String, Quantity>();
                    if(!StringUtil.isEmpty(appBaseInfoBean.getRequestCpu())){
                        Quantity quantity_r_cpu = new QuantityBuilder()
                                .withAmount(appBaseInfoBean.getRequestCpu())
                                .build();
                        requestsMap.put("cpu", quantity_r_cpu);
                    }
                    if(!StringUtil.isEmpty(appBaseInfoBean.getRequestMemory())){
                        Quantity quantity_r_memory = new QuantityBuilder()
                                .withAmount(appBaseInfoBean.getRequestMemory())
                                .build();
                        requestsMap.put("memory", quantity_r_memory);
                    }
                    container.getResources().setRequests(requestsMap);

                    if(!StringUtil.isEmpty(appBaseInfoBean.getLimitsCpu())){
                        Quantity quantity_l_cpu = new QuantityBuilder()
                                .withAmount(appBaseInfoBean.getLimitsCpu())
                                .build();
                        limitsMap.put("cpu", quantity_l_cpu);
                    }

                    if(!StringUtil.isEmpty(appBaseInfoBean.getLimitsMemory())){
                        Quantity quantity_l_memory = new QuantityBuilder()
                                .withAmount(appBaseInfoBean.getLimitsMemory())
                                .build();
                        limitsMap.put("memory", quantity_l_memory);
                    }
                    container.getResources().setLimits(limitsMap);
                }else if(appBaseInfoBean.getUpdateType()==1){
                    container.setCommand(appBaseInfoBean.getCommand());
                    container.setArgs(appBaseInfoBean.getArgs());
                }else if(appBaseInfoBean.getUpdateType()==2){
                    //container.setEnv();
                    List<EnvVar> envVarList=new ArrayList<>();
                    for(Map<String,String> env:appBaseInfoBean.getEnvs()){
                        EnvVar envVar=new EnvVar();
                        envVar.setName(env.get("name"));
                        envVar.setValue(env.get("value"));
                        envVarList.add(envVar);
                    }
                    container.setEnv(envVarList);
                }

            }

        //更新
        if (AppManageConfigBean.Kind_Deployment.indexOf(appBaseInfoBean.getAppKind()) != -1) {
            Deployment deployment1 = k8sManageService.getK8sClient().apps().deployments().inNamespace(appBaseInfoBean.getNamespace()).withName(appBaseInfoBean.getAppNameKube()).createOrReplace(deployment);
            if(deployment1!=null){
                return true;
            }
        } else if (AppManageConfigBean.Kind_StatefulSet.indexOf(appBaseInfoBean.getAppKind()) != -1) {
            StatefulSet statefulSet1 = k8sManageService.getK8sClient().apps().statefulSets().inNamespace(appBaseInfoBean.getNamespace()).withName(appBaseInfoBean.getAppNameKube()).createOrReplace(statefulSet);
            if(statefulSet1!=null){
                return true;
            }
        } else if (AppManageConfigBean.Kind_DaemonSet.indexOf(appBaseInfoBean.getAppKind()) != -1) {

        }

        return false;
    }

}
